编程语言
首页 > 编程语言> > javascript-移动Safari,scrollIntoView不起作用

javascript-移动Safari,scrollIntoView不起作用

作者:互联网

我在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);
}

解决方法:

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补充此代码

标签:javascript,ios,safari,mobile-safari,iframe
来源: https://codeday.me/bug/20191010/1888856.html