html代码:
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Javascript 回到顶部效果</title>
<link href="~/Content/test.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/JS/test.js"></script>
</head>
<body>
<div class="box">
<img src="535e0ce800015b7511902787.jpg" />
</div>
<a href="javascript:;" id="btn" title="回到顶部"></a>
</body>
</html>
css代码:
#btn {
40px;
height: 40px;
position: fixed;
left: 50%;
margin-left: 610px;
bottom: 30px;
display:none;
background: url(535e0dc100010e9c00400080.jpg) no-repeat left top;
}
#btn:hover {
background: url(535e0dc100010e9c00400080.jpg) no-repeat 0 -39px;
}
.box {
1190px;
margin: 0 auto;
}
js代码:
//页面加载完毕后触发
window.onload = function () {
var obtn = document.getElementById("btn");
var clientHeight = document.documentElement.clientHeight;
var timer = null;
var isTop = true;
//滚动条滚动时触发
window.onscroll = function () {
var osTop = document.documentElement.scrollTop || document.body.scrollTop;
if (osTop >= clientHeight) {
obtn.style.display = "block";
} else {
obtn.style.display = "none";
}
if (!isTop) {
clearInterval(timer);
}
isTop=false;
}
obtn.onclick = function () {
//设置定时器
timer = setInterval(function () {
//获取滚动条距离顶部的高度
var osTop = document.documentElement.scrollTop || document.body.scrollTop;
var ispeed = Math.floor(-osTop / 3);
document.documentElement.scrollTop = document.body.scrollTop = osTop + ispeed;
isTop = true;
console.log(osTop - ispeed);
if (osTop == 0) {
clearInterval(timer);
}
}, 30);
}
}