html部分:
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
*{
margin:0;
padding:0
}
a {
width:40px;
height:40px;
background:url(top_bar.png) no-repeat left top;
position:fixed;
left:50%;
margin-left:520px;
display:none;
}
a:hover{
background:url(top_bar.png) no-repeat left -40px;
}
</style>
</head>
<body>
<a href="javascript:;" title="回到顶部" id="btn"></a>
</body>
</html>
javascript部分
//页面加载完执行
window.onload = function(){
var obtn = document.getElementById("btn");
var timer = null;
var isTop = true;
//滚动条滚动时触发
window.onscroll = function(){
//获取滚动条距离顶部的距离
var osTop = document.documentElement.scrollTop || document.body.scrollTop;
var clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
if(osTop>=clientHeight)[
obtn.style.display = "block";
}else[
obtn.style.display = "none";
}
if(!isTop){
clearInterval(timer);
}
isTop = false;
}
obtn.onclick = function(){
//获取滚动条距离顶部的位置
var osTop = document.documentElement.scrollTop || document.body.scrollTop;
var speed = Math.ceil(osTop / 6);
isTop = true;
timer = setInterval(function(){
document.documentElement.scrollTop = document.body.scrollTop = osTop - speed;
if(osTop == 0){
clearInterval(timer);
}
},30)
}
}
网友评论