html:
<ul> //撑页面
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
<a href="javascript:;" id="btn"><p>回到顶部</p></a> //回到顶部按钮
css:
body,ul,li,p{
margin: 0;
padding: 0;
}
ul{
list-style: none;
width: 600px;
margin: 0 auto;
}
li{
width: 600px;
height: 300px;
text-align: center;
line-height: 300px;
font-size: 80px;
}
#btn{
width: 40px;
height: 40px;
position: fixed; //注意定位的位置
left: 50%;
margin-left: 330px;
bottom: 30px;
background: #ccc;
text-decoration: none;
color: #333333;
font-size: 14px;
text-align: center;
display: table;
display: none;
}
#btn:hover{
background: orchid;
color: #FFFFFF;
}
#btn p{
display: table-cell; //多行文字的垂直居中效果
vertical-align: middle;
}
js:
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='table';
}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/7);
document.documentElement.scrollTop=document.body.scrollTop=osTop+iSpeed;
isTop=true;
if (osTop==0) { //回到顶部后清除定时器
clearInterval(timer);
}
},30)
}