JavaScript 只能跨浏览器平滑滚动
JavaScript only smooth scrolling across browsers
我有一个在 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);
我有一个在 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);