我在 iframe 的移动 Safari 上滚动到元素时遇到问题(它适用于其他浏览器,包括 mac 上的 Safari)。
我使用 scrollIntoView
。我想在呈现所有内容后滚动。这是我的代码:
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 移动设备,但您可以使用此 polyfill 补充此代码
关于javascript - 移动 Safari,scrollIntoView 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45098593/