简体   繁体   English

我在网站上有一个返回页面顶部的按钮,如何动画化返回顶部的动画?

[英]I have a return to top of the page button in my website, how can I animate scrolling back to the top?

I already have a button in my html and css that appears when the user scrolls down 20px. 我的html和CSS中已经有一个按钮,当用户向下滚动20px时出现。 When you click the button, it sends the user back to the top of the page. 当您单击按钮时,它将使用户返回页面顶部。 I would like it to animate scrolling back to the top, instead of jumping straight there. 我希望它动画返回顶部,而不是直接跳到顶部。 Here's my code: 这是我的代码:

HTML: HTML:

<button onclick="topFunction()" id="myBtn" title="Return To Top"><i class="fa fa-angle-up fa-lg"></i></button>

CSS: 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: 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
}

Any help is welcome 欢迎任何帮助

Use the .animate() function with scrollTop like this: .animate()函数与scrollTop如下所示:

function topFunction() {
   $("html, body").animate({scrollTop: "0"});
}

you could use the jQuery .animate() method, and the scrollTop property. 您可以使用jQuery .animate()方法和scrollTop属性。

Example: 例:

$(function(){
    $("#myBtn").click(function(e){
        e.preventDefault();
        $("html, body").animate({"scrollTop": "0px"}, 600);
    })
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM