2017-04-02 85 views
0

我已经有一个按钮在我的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 
} 

欢迎任何帮助

+0

看看这个:http://stackoverflow.com/a/1145297/6483483 – blackandorangecat

回答

1

使用.animate()功能与scrollTop是这样的:

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

可以调节速度,如果你想为好。 ();或者$(“html,body”)。animate({scrollTop:0},“fast”);'或'$(“html,body”)。animate({scrollTop:0},“1000”);'。默认是400ms。手册:https://www.w3schools.com/jquery/eff_animate.asp – blackandorangecat

0

您可以使用jQuery.animate()方法,以及scrollTop财产。

例子:

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