簡體   English   中英

滾動到頂部按鈕不會出現

[英]Scroll-to-top button won't appear

嘿嘿,

我不是開發人員,但正在嘗試為我的婚禮慶典設置一個小型私人網頁,並想添加一個滾動到頂部的按鈕。 我正在使用 VSC 手動對網站進行編程。 我的問題是我可以使用 HTML 和 CSS 生成按鈕,但是 JS 似乎不起作用,我不知道出了什么問題。 是的,在瀏覽器中啟用了 JS。

所以我在 HTML 中添加了這個按鈕:

<button onclick="topFunction()" id="myBtn" title="Go to top">Top</button>

並在 HTML 頁面 header 中鏈接 my.js 文件

<script type="text/javascript" src="javascript.js"> </script>

然后我添加 CSS:

#myBtn {
    display: none;
    position: fixed;
    bottom: 20px;
    right: 30px;
    z-index: 99;
    border: none;
    outline: none;
    background-color: red;
    color: white;
    cursor: pointer;
    padding: 15px;
    border-radius: 10px;
    font-size: 18px;
}

#myBtn:hover {
    background-color: #555;
}

當我將顯示屬性設置為“阻止”時,按鈕會顯示它應該在的位置。 hover 效果也可以正常工作。

然后我添加了.js文件; 實際上,我只是從 W3Schools 復制並粘貼代碼。 當它不起作用時,我試圖擺弄它,但沒有找到解決方案。

該按鈕應該在頁面向下滾動 20px 時出現,並在它更少時消失。 但是,無論我滾動頁面多遠,按鈕都不會出現。

//Get the button:
mybutton = document.getElementById("myBtn");

// When the user scrolls down 20px from the top of the document, show the 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";
  }
}

// When the user clicks on the button, scroll to the top of the document
function topFunction() {
  document.body.scrollTop = 0; // For Safari
  document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
} 

如果有人可以幫助我,那就太好了。

我在<body>元素中添加了<button>元素,並為<body> body> 元素提供了高度,以便可以觸發onscroll事件。 在這種情況下,當onscroll事件被觸發時<button>可以正常工作。 必須打開滾動條才能觸發onscroll事件。 頁面height必須大於滾動條打開的全屏高度。

 mybutton = document.getElementById("myBtn"); window.onscroll = function() { scrollFunction() } function scrollFunction() { console.log(document.body.scrollTop ) console.log(document.documentElement.scrollTop) 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; }
 /* I added height style to the <body> element. */ body{ height: 1000px; } #myBtn { display: none; position: fixed; bottom: 20px; right: 30px; z-index: 99; border: none; outline: none; background-color: red; color: white; cursor: pointer; padding: 15px; border-radius: 10px; font-size: 18px; } #myBtn:hover { background-color: #555; }
 <body> <button onclick="topFunction()" id="myBtn" title="Go to top">Top</button> </body>

我知道了。 菜鳥的錯誤,我猜。 我將腳本標簽放在 HTML 文件的 header 中。 當我把它們放在身體的末端時,它工作得很好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM