繁体   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