簡體   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