html代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<script src="js/app.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div class="box">
<img src="img/jkxy.png"/>
</div>
<a style="display: none;" href="javascript:;" class="btn" title="回到顶端" id="btn"></a> <!-- href设置值为Javascript:; 去除直接跳转到顶端的效果-->
</body>
</html>
css代码:
*{
margin: 0;
padding: 0;
}
.box {
width: 1000px;
margin: 0 auto;
}
.btn {
width: 40px;
height: 80px;
position: fixed;
bottom: 30px;
background: red;
left: 50%;
margin-left: 500px;
}
.btn:hover {
background: green;
}
JavaScript代码:
window.onload = function(){
var topbtn = document.getElementById("btn");
var timer = null;
var pagelookheight = document.documentElement.clientHeight; //获取一个屏幕的距离
window.onscroll = function(){ //滚动调用事件
//获取屏幕滚动的高度
var bactop = document.body.scrollTop;
if (bactop >= pagelookheight) {
// 滚动超过一屏的距离显示回到顶部..否则不显示
topbtn.style.display = "block";
} else {
topbtn.style.display = "none";
}
}
topbtn.onclick = function(){
timer = setInterval(function(){
var bactop = document.body.scrollTop; //屏幕滚动的高度
var speedtop = bactop / 5; //设置速度越来越慢, 在滚动到顶端的时候速度达到最慢
document.body.scrollTop = bactop - speedtop;
if (bactop == 0) {
clearInterval(timer); //消除计时器
}
}, 30);
}
}