js方法:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
#top{
display: block;text-decoration:none;text-align:center;
width:40px;height:40px;line-height:40px;border-radius:5px;background:#000;
position: fixed;right:0;bottom:60px;
display: none;
}
</style>
</head>
<body style="height: 2500px;background: #ccc;">
<div class="container">
<a href="javascript:;" id="top" title="回到顶部">TOP</a>
</div>
<script type="text/javascript">
window.onload = function(){
var oBtn = document.getElementById("top"),
timer = null,
clientH = document.documentElement.clientHeight || document.body.clientHeight;
window.onscroll = function(){
var osTop = document.documentElement.scrollTop || document.body.scrollTop;
if(osTop >= clientH){
oBtn.style.display = "block";
}else{
oBtn.style.display = "none"
}
}
oBtn.onclick = function(){
timer = setInterval(function(){
var osTop = document.documentElement.scrollTop || document.body.scrollTop;
var ospeed = Math.floor(-osTop/10);
document.documentElement.scrollTop = document.
body.scrollTop = osTop+ospeed;
if(osTop == 0){
clearInterval(timer);
}
},30);
}
}
</script>
</body>
</html>
再来看看jquery方法,简单了许多
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
.content{position: absolute;}
button{
width:100px;height:30px;background: skyblue;
position: fixed;bottom:60px;right:20px;
display: none;
}
</style>
</head>
<body style="height: 2500px;background: #ccc;">
<button id="back-top">TOP</button>
<script type="text/javascript" src="./js/jquery-3.1.1.js"></script>
<script type="text/javascript">
$(function(){
//"use strict"
var backTopBtn = $("#back-top");
backTopBtn.on("click",function(){
$('html,body').animate({
scrollTop:0
},800);
});
$(window).on("scroll",function(){
if($(window).scrollTop() > $(window).height()){
backTopBtn.fadeIn();
}else{
backTopBtn.fadeOut();
}
});
//trigger激活时间,每次刷新时自动监听滚动事件
$(window).trigger("scroll");
})
</script>
</body>
</html>