功能:
1.按钮在滚动调滚动到第二屏时显示;
2.点击按钮,滚动条由快到慢回到顶部;
3.回到顶部过程中若鼠标滚动滚动条则停止回到顶部;
HTML代码:
<body>
<div class="container">
<img src="images/tb_bg.jpg">
</div>
<a href="javascript:;" id="btn" title="回到顶部">
</a>
</body>
css代码:
*{
padding:0;
margin:0;
}
.container{
width: 1190px;
margin: 0 auto;
position: relative;
}
#btn{
width: 40px;
height: 40px;
overflow: hidden;
position: fixed;
right: 20px;
bottom: 20px;
background: url("images/top_bg.png") no-repeat left top;
display: none;
}
#btn:hover{
width: 40px;
height: 40px;
background: url("images/top_bg.png") no-repeat left -40px;
}
js代码:
<script type="text/javascript">
function addLoadEvent(func){
var oldοnlοad=window.onload;
if(typeof window.onload!='function'){
window.οnlοad=func();
}
else{
window.οnlοad=function(){
oldonload();
func();
}
}
}
function startMain(){
var btn=document.getElementById("btn");
var timer=null;//定时器
var isGoUp=true;//滚动条在滚动
var clientHeight=document.documentElement.clientHeight;//获取页面可视区的高度
//滚动条滚动时触发
window.οnscrοll=function(){
var distance=document.documentElement.scrollTop||document.body.scrollTop;
if(distance>=clientHeight){
btn.style.display='block';
}else{
btn.style.display='none';
}
if(!isGoUp){
clearInterval(timer);
}
isGoUp=false;
};
btn.οnclick=function(){
timer=setInterval(function(){
//获取与顶部的距离
isGoUp=true;
var distance=document.documentElement.scrollTop||document.body.scrollTop;//兼容IE
if(distance==0){
clearInterval(timer);
}
//减少距离顶部的距离
var speed=Math.floor(-distance/6);
document.documentElement.scrollTop=document.body.scrollTop=distance+speed;
// console.log(distance);
},30)
}
}
addLoadEvent(startMain);
</script>