移动Safari,scrollIntoView无法正常工作

时间:2017-07-14 08:47:27

标签: javascript ios iframe safari mobile-safari

我在iframe的移动版Safari上滚动到元素时遇到问题(它适用于其他浏览器,包括Mac上的Safari)。

我使用scrollIntoView。我想在渲染所有contnet时滚动。这是我的代码:

var readyStateCheckInterval = setInterval(function () {
    if (document.readyState === "complete") {
       clearInterval(readyStateCheckInterval);
        $browser.notifyWhenNoOutstandingRequests(function () {
            if (cinemaName != null && eventId == null) {
                scrollToCinema();
            } else {
                scrollToEvent();
            }
        });
     }
}, 10);


function scrollToEvent() {
    var id = eventId;
    var delay = 100;

    if (cinemaName != null) {
        id = cinemaName + "#" + eventId;
    }

    if ($rootScope.eventId != null) {
        id = $rootScope.cinemaId + "#" + $rootScope.eventId;
    }

    $timeout(function () {
        var el = document.getElementById(id);
        if (el != null)
        el.scrollIntoView(true);    
        $rootScope.eventId = null;
    }, delay);
}

3 个答案:

答案 0 :(得分:2)

ScrollIntoView不起作用(当前)。但您可以手动计算元素的位置并滚动到它。这是我的解决方案

const element = document.getElementById('myId')

将元素传递给此函数

/** Scrolls the element into view
 * Manually created since Safari does not support the native one inside an iframe
*/
export const scrollElementIntoView = (element: HTMLElement, behavior?: 'smooth' | 'instant' | 'auto') => {

  let scrollTop = window.pageYOffset || element.scrollTop

   // Furthermore, if you have for example a header outside the iframe 
   // you need to factor in its dimensions when calculating the position to scroll to
   const headerOutsideIframe = window.parent.document.getElementsByClassName('myHeader')[0].clientHeight

  const finalOffset = element.getBoundingClientRect().top + scrollTop + headerOutsideIframe

  window.parent.scrollTo({
    top: finalOffset,
    behavior: behavior || 'auto'
  })
}

陷阱:平滑滚动也不适用于ios mobile,但您可以使用此polyfill

补充此代码

答案 1 :(得分:0)

您最有可能遇到我刚刚调试过的相同问题。 Safari会自动调整框架的大小以适合其内容。因此,iframe的父级将在Safari中具有滚动条。因此,从iframe自身内部调用scrollintoview会“失败”。

如果Iframe是跨域的,则通过window访问父文档。parent.document将被拒绝。

如果您需要跨域解决方案,请查看我的答案here.

基本上,我使用帖子消息告诉父页面在Mobile Safari跨域内部时进行滚动。

答案 2 :(得分:0)

以我的经验,scrollIntoView()有时在我的iphone和ipad上会失败,有时会起作用(在我自己的网站上)。我没有使用iframe。在上述设备上的Safari和Firefox中都是如此。

对我有用的解决方案是将您需要滚动的元素弹出到DIV中,例如。作为该DIV中的第一个元素。嘿,然后就可以了! 似乎是苹果公司的狡猾实施。

相关问题