<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{
margin:0;
padding:0;
font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
font-size: 14px;
-webkit-user-select: none ;
}
html,body{
width:100%;
height:500%;;
background: #11c900;
background: -webkit-linear-gradient(top,#11c900,lightblue,lightcoral,
lightcyan,lightgoldenrodyellow,lightgreen,lightpink,lightsalmon,lightseagreen);
}
/*清除a以及a的伪类的默认样式*/
a{
text-decoration: none;
color:#000;
}
a:hover,a:active,a:target,a:visited{
text-decoration: none;
color:#000;
}
#goLink{
/*display: block;*/
display:none;/*刚开始隐藏按钮*/
position:fixed;/*加了position就默认是块状了,可以不用display设置*/
bottom:200px;
right:50px;
width:50px;
height:50px;
line-height: 50px;
text-align: center;
background: red;
border-radius:50%;
opacity: 0.5;
filter:alpha(opacity=50)
}
#goLink:hover{
opacity: 100;
filter:alpha(opacity=100);
}
#target{
margin:1000px auto;
height:50px;
background: red;
}
</style>
</head>
<body>
<!--取消默认跳转-->
<a href="#javascript:;" id="goLink">GO</a>
<!--设置一个点击事件,点击回到顶部-->
<script type="text/javascript">
var goLink=document.getElementById("goLink");
//改进1:如下
//开始GO按钮是不显示的,当卷去的高度超过一屏幕的高度时才显示,反之隐藏,只要浏览器的滚动条在滚动,就需要判判断那GO显示还是隐藏
//浏览器的滚动条滚动:拖动滚动条、鼠标滚动、键盘上下键、pageDown/pageUp、点击滚动条空白处/箭头(自主操作行为),还可以通过JS控制scrollTop值
window.onscroll=computedDisplay; //无论怎么操作,只要滚动条动了,就会触发这个行为
function computedDisplay(){ //把函数写成实名函数,方便下面调用
var curTop=document.documentElement.scrollTop||document.body.scrollTop;//当前卷去的高度
var curHeight=document.documentElement.clientHeight||document.body.clientHeight;//一屏幕的高度
goLink.style.display=curTop>curHeight?"block":"none";//当前卷去的高度超过一屏幕的高度时,显示
};
//回到顶部:
//1、总时间(duration):500ms
//2、频率(interval):多长时间走一步:10ms
//3、总距离target:当前的位置(当前的scrollTop值)-目标的位置(0)
//4、步长(step)每一次走的距离:target/duration:每一毫秒走的距离*interval:每一次走的距离
goLink.onclick=function(){
//改进2:当点击的时候让当前的GO消失,
this.style.display="none";
//光这样还不行,往回走的时候,滚动条动,又把window.onscroll行为触发了,让GO又显示了
//我们需要再点击后,把window.onscroll绑定的事件取消掉
window.onscroll=null;
//当点击GO的时候,首先把每一步要走的步长计算出来
var duration=500,interval=10,target=document.documentElement.scrollTop||document.body.scrollTop;
var step=(target/duration)*interval
//计算完步长后,让当前页面每隔interval这么长的时间走一步,在上一次的scrollTop的基础上-步长
var timer=window.setInterval(function(){
var curTop=document.documentElement.scrollTop||document.body.scrollTop;
if(curTop===0){//已经走到头了
window.clearInterval(timer);
window.onscroll=computedDisplay; //当动画结束后还需要把对应的方法重新绑定给window.onscroll
return;
}
curTop-=step;//当前的位置等于上一步的位置-步长
document.documentElement.scrollTop=curTop;//重新计算目前卷去的高度
document.body.scrollTop=curTop;
},interval)
//document.documentElement.scrollTop=0;
//document.body.scrollTop=0;
}
</script>
</body>
</html>