gpt4 book ai didi

JavaScript 仅能在浏览器之间平滑滚动

转载 作者:行者123 更新时间:2023-11-28 18:22:35 26 4
gpt4 key购买 nike

我有一个平滑滚动功能,在 Chrome 和 Safari 中运行良好,但在 Firefox 中无法运行,因为它正在调用 document.body.scrollTop

function smoothScroll(body, destination, duration) {
duration = (typeof duration != "undefined")
? duration
: 500;
if (duration <= 0) return;
var difference = destination - body.scrollTop;
var perTick = difference / duration * 10;
setTimeout(function() {
body.scrollTop = body.scrollTop + perTick;
if (body.scrollTop === destination) {
showAndHideNav("hide");
return;
}
smoothScroll(body, destination, duration - 10);
}, 10);
}

function findDestination(element) {
var value = element.getAttribute("value"),
destination = document.getElementById(value).offsetTop;
return destination;
}

smoothScroll(document.body, findDestination(element));

我尝试将 scrollTop 替换为 pageYOffset,它标识正确的位置,但不会滚动到这些位置。

谁能推荐一个对浏览器更友好的 scrollTop 替代方案,以实现跨浏览器的平滑滚动?

感谢您的帮助!

最佳答案

不要直接使用 body.scrollTop,而是尝试使用以下辅助函数,如下所示:getScrollTop(window)

function getScrollTop(scrollable) {
return scrollable.scrollTop || document.body.scrollTop || document.documentElement.scrollTop;
}

要实际滚动到目标,请尝试以下跨浏览器方法:

window.scrollTo(0, getScrollTop(window) + perTick);

关于JavaScript 仅能在浏览器之间平滑滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39687858/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com