簡體   English   中英

過渡到滾動返回頂部按鈕

[英]Transition to a scroll back to top button

我按照本教程在我的網站上創建了一個按鈕以滾動回我的頁面頂部: W3Schools

問題是當你點擊按鈕時,沒有過渡到頂部,你只是“傳送”到頁面頂部。 因此,如果有人知道如何改進過渡或如何制作按鈕。

HTML 代碼:

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

CSS 代碼:

#myBtn {
  display: none; /* Hidden by default */
  position: fixed; /* Fixed/sticky position */
  bottom: 20px; /* Place the button at the bottom of the page */
  right: 30px; /* Place the button 30px from the right */
  z-index: 99; /* Make sure it does not overlap */
  border: none; /* Remove borders */
  outline: none; /* Remove outline */
  background-color: red; /* Set a background color */
  color: white; /* Text color */
  cursor: pointer; /* Add a mouse pointer on hover */
  padding: 15px; /* Some padding */
  border-radius: 10px; /* Rounded corners */
  font-size: 18px; /* Increase font size */
}

#myBtn:hover {
  background-color: #555; /* Add a dark-grey background on hover */
}

JavaScript 代碼:

//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
}

您可以通過添加scroll-behavior: smooth;來做到這一點。 到您的html styles 或使用 window scrollTo方法和選項behavior: 'smooth'在您的Z9E37102B69D1D25DA9中“平滑”

window.scrollTo({
  top: 0,
  left: 0,
  behavior: 'smooth'
});

在你的topFunction()中試試這個,它應該可以正常工作。 您可以為動畫命令設置回調 function。 我已經在我的本地主機中進行了測試,它就像一個魅力。 希望對您有所幫助。

 function topFunction() {
     var body = $("html, body");
      body.stop().animate({scrollTop:0}, 500, 'swing', function() { 
           console.log("Animation has finished");
      });
    }

按照我在下面給出的結構。

<!Doctype html>
<html>
<head>
<!--Add the CSS Code here-->
<style>
</style>
</head>
<body>
<!--Add more text here-->
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum....</p>
<button onclick="topFunction()" id="myBtn" title="Go to top">Top</button>
</body>
<script>
<!--Add the JavaScript Code here-->
</script>
</html>```
Then just run the code.

暫無
暫無

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

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