移动Safari,scrollIntoView不起作用 [英] Mobile Safari, scrollIntoView doesn't work

查看:2242
本文介绍了移动Safari,scrollIntoView不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have problem with scroll to element on mobile Safari in iframe(it works on other browsers, including Safari on mac).

我使用scrollIntoView.当所有contnet都呈现后,我想滚动.这是我的代码:

I use scrollIntoView. I want to scroll when all contnet has been rendered. Here is my code:

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当前不起作用.但是您可以手动计算元素的位置并滚动到它.这是我的解决方法

ScrollIntoView does not work (currently). But you can manually calculate the position of the element and scroll to it. Here is my solution

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

Pitfalls: Smooth scroll also does not work for ios mobile, but you can complement this code with this polyfill

这篇关于移动Safari,scrollIntoView不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆