繁体   English   中英

在页面顶部时,Javascript> HTML滚动按钮不会消失

[英]Javascript > HTML scroll button doesn't dissapear when at top of page

因此,我现在就建立一个网站,并设置一个按钮,当您向下滚动一小段距离时,它应该会出现,并且当您单击它时,它会将您带到页面顶部。 但是由于某种原因,即使我在顶部,按钮也始终可见,这是我的代码:

 document.getElementById("scrollButton").onclick = goToTop(); window.onscroll = function() { "use strict"; scrollFunction(); }; function scrollFunction() { "use strict"; if ((document.body.scrollTop > 20) || (document.documentElement.scrollTop > 20)) { document.getElementById("scrollButton").style.display = "block"; } else { document.getElementById("scrollButton").style.display = "none"; } } function goToTop() { "use strict"; document.body.scrollTop = 0; document.documentElement.scrollTop = 0; } 
 .scrollButton { position: fixed; bottom: 20px; right: 30px; z-index: 99; font-size: 18px; border: none; outline: none; background-color: red; color: white; cursor: pointer; padding: 15px; border-radius: 4px; } .scrollButton:hover { background-color: #555; } #fill { height: 150vh } 
 <div id='fill'></div> <button onclick="goToTop();" class="scrollButton" id="scrollButton" title="Go to top">Top</button> 

我不确定是什么问题,在javascript中的“ scrollFunction()”上,它说当我向下滚动时,它应该使它出现,但是当我在顶部时,它应该消失,但是没有。 有人知道为什么吗?

您需要默认设置display:none

 document.addEventListener('DOMContentLoaded', function() { scrollFunction(); }) document.getElementById("scrollButton").onclick = goToTop; window.onscroll = function() { "use strict"; scrollFunction(); }; function scrollFunction() { "use strict"; if ((document.body.scrollTop > 20) || (document.documentElement.scrollTop > 20)) { document.getElementById("scrollButton").style.display = "block"; } else { document.getElementById("scrollButton").style.display = "none"; } } function goToTop() { "use strict"; document.body.scrollTop = 0; document.documentElement.scrollTop = 0; } 
 .scrollButton { position: fixed; bottom: 20px; right: 30px; z-index: 99; font-size: 18px; border: none; outline: none; background-color: red; color: white; cursor: pointer; padding: 15px; border-radius: 4px; } .scrollButton:hover { background-color: #555; } #fill { height: 150vh } 
 <div id='fill'></div> <button onclick="goToTop();" class="scrollButton" id="scrollButton" title="Go to top">Top</button> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM