[英]Scroll back to top button using JavaScript appears all the time
I created a scroll back to top button, which I would like to appear on the page only after the page was scrolled down a bit.我创建了一个滚动回到顶部按钮,我希望它只在页面向下滚动一点后出现在页面上。 However, the button appears when opening the page for the first time, but after scrolling down and up again it disappears - acting therefore as it should.
但是,该按钮在第一次打开页面时出现,但在再次向下和向上滚动后它会消失 - 因此按应有的方式运行。 I looked too much over the code and can't see where the issue is anymore:) How should I change the code below so that the button will appear only after scrolling?
我看了太多代码,看不出问题出在哪里了:)我应该如何更改下面的代码,以便按钮仅在滚动后出现?
HTML part: HTML部分:
<button onclick="topFunction()" id="button" title="Go to the top">^</button>
JavaScript part: JavaScript部分:
var myButton = document.getElementById("button");
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
myButton.style.display = "block";
}
else {
myButton.style.display = "none";
}
}
function topFunction() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
Thank you for your time!感谢您的时间!
Hide it by default is probably the best option to avoid glitching/flashing.默认隐藏它可能是避免故障/闪烁的最佳选择。
<button style="display: none;" onclick="topFunction()" id="button" title="Go to the top">^</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.