移动Safari,scrollIntoView不起作用

ksz*_*ram 5 javascript safari iframe mobile-safari ios

我在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);
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*oal 13

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

const element = document.getElementById('myId')
Run Code Online (Sandbox Code Playgroud)

将元素传递给这个函数

/** 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'
  })
}
Run Code Online (Sandbox Code Playgroud)

陷阱:平滑滚动也不适用于 ios 移动设备,但您可以使用此polyfill补充此代码


小智 5

根据我的经验,scrollIntoView() 在我的 iphone 和 ipad 上有时会失败,有时却可以(在我自己的网站上)。我没有使用 iframe。上述设备上的 safari 和 firefox 都是如此。

对我有用的解决方案是弹出您需要滚动到 DIV 内部的元素,例如。作为该 DIV 中的第一个元素。嘿,很快就可以正常工作了!看起来苹果的实施方式很狡猾。