[英]I have a return to top of the page button in my website, how can I animate scrolling back to the top?
我的html和CSS中已經有一個按鈕,當用戶向下滾動20px時出現。 當您單擊按鈕時,它將使用戶返回頁面頂部。 我希望它動畫返回頂部,而不是直接跳到頂部。 這是我的代碼:
HTML:
<button onclick="topFunction()" id="myBtn" title="Return To Top"><i class="fa fa-angle-up fa-lg"></i></button>
CSS:
#myBtn {
display: none;
font-size: 2em;
position: fixed;
bottom: 20px;
right: 30px;
z-index: 99;
border: none;
outline: none;
background-color: rgba(0, 0, 0, 0.5);
color: white;
cursor: pointer;
padding: 15px;
border-radius: 10px;
-webkit-transition: color 0.5s;
transition: color 0.5s;
}
#myBtn:hover {
color: #00ff0a;
}
Javascript:
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
document.getElementById("myBtn").style.display = "block";
} else {
document.getElementById("myBtn").style.display = "none";
}
}
// When the user clicks on the button, scroll to the top of the document
function topFunction() {
document.body.scrollTop = 0; // For Chrome, Safari and Opera
document.documentElement.scrollTop = 0; // For IE and Firefox
}
歡迎任何幫助
將.animate()
函數與scrollTop
如下所示:
function topFunction() {
$("html, body").animate({scrollTop: "0"});
}
您可以使用jQuery
.animate()方法和scrollTop
屬性。
例:
$(function(){
$("#myBtn").click(function(e){
e.preventDefault();
$("html, body").animate({"scrollTop": "0px"}, 600);
})
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.