<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JS实现效果-点击按钮返回到页面顶部</title>
<style>
#container{margin:0;padding:0;}
#box1,#box2,#box3,#box4{width:100%;height:500px;}
#box1{background: deepskyblue;}
#box2{background: yellowgreen;}
#box3{background: darkred;}
#box4{background: blueviolet;}
#icon{width:50px;height:50px;font-size: 20px;background: #CDCC7D;line-height: 50px;text-align: center;position: fixed;bottom:20px;right:20px;color:#666;font-weight: bolder;}
</style>
</head>
<body>
<div id="container">
<div id="box1"></div>
<div id="box2"></div>
<div id="box3"></div>
<div id="box4"></div>
<div id="icon">↑</div>
</div>
</body>
<script type="text/javascript">
window.onload = function(){
var btn = document.getElementById("icon");
var timer = null;
var oScroll = true;
//滚动条事件,触发时清空定时器
window.onscroll = function(){
if(!oScroll){
clearInterval(timer);
}
oScroll = false;
}
btn.onclick = function(){
//加入定时器让他又快到慢滚动到顶部
timer = setInterval(function(){
//获取当前scrollTop的高度位置(兼容ie和chrom浏览器)
var oTop = document.documentElement.scrollTop || document.body.scrollTop;
//设置速度由快到慢
var ispeed = Math.floor(-oTop / 7);
document.documentElement.scrollTop = document.body.scrollTop = oTop + ispeed;
oScroll = true;
if(oTop == 0){
clearInterval(timer);
}
},30);
}
}
</script>
</html>
以上代码直接粘贴复制即可查看效果,兼容ie和chrome浏览器!!!