如何使用 vanilla JavaScript 滚动到顶部?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14405180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:32:53 来源:igfitidea点击:
How to scroll to the top using vanilla JavaScript?
提问by Neo
I'm trying to imitate scrollTop
(jQuery) in vanilla JS, so on click it scrolls to an element. This works fine - unless you have already scrolled past the element. So it doesn't scroll the opposite way. Should my formula incorporate window.pageYOffset
?
我正在尝试scrollTop
在 vanilla JS 中模仿(jQuery),因此单击它会滚动到一个元素。这工作正常 - 除非您已经滚动过该元素。所以它不会以相反的方式滚动。我的公式应该包含window.pageYOffset
吗?
var moves = function(scrollz) {
var scrollPos = document.getElementById(scrollz).offsetTop - ((document.documentElement.clientHeight - document.getElementById(scrollz).offsetHeight) / 2);
var timerID = setInterval(function() {
window.scrollBy(0, speed);
if (window.pageYOffset >= scrollPos) {
clearInterval(timerID);
}
}, 13);
}