首页 > Web开发 > 详细

原生js实现缓动返回顶部

时间:2017-09-03 10:53:59      阅读:320      评论:0      收藏:0      [点我收藏+]

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{
padding: 0;
margin: 0;
}
#box{
width: 1366px;
height: 2000px;
position: absolute;
background-color: lightcoral;
}
button{
width: 100px;
height: 35px;
background-color: lawngreen;
position: fixed;
top: 75%;
right: 0;
display: none;
}
</style>
</head>
<body>
<div id="box">
<button>返回顶部</button>
</div>
</body>
<script type="text/javascript">
var btn = document.getElementsByTagName(‘button‘)[0];
document.onscroll = function(){
if (scroll().top > 300) {
// 高度大于300显示
btn.style.display = "block";
// 将leader的值传入
leader = scroll().top;
} else{
// 小于300隐藏
btn.style.display = "none";
}

}
var target = 0,leader = 0,timer = null;
var box = document.getElementById(‘box‘);
btn.onclick = function(){
clearInterval(timer);
timer = setInterval(function(){
// target 目标值 leader初始时是滚动的高度
var step = (target - leader)/10;
// 如果大于0向上取整小于0向下取整
step = step > 0 ? Math.ceil(step) : Math.floor(step);
// leader发生改变
leader = leader + step;
// 返回到哪一个地方
window.scrollTo(0,leader);
if (leader == target) {
clearInterval(timer);
}
},30)
}

/*
* 获取水平方向/垂直方向,滚动的距离。
* document.documentElement.scrollLeft
* 兼容性
* 返回顶部:window.scrollTo(x,y) 指定滚动到的位置
* 返回顶部:window.scrollTo(0,0) 指定滚动到的位置
*
*/

function scroll() {
if(window.pageYOffset != null) // ie9+ 和其他浏览器
{
return {
left: window.pageXOffset,
top: window.pageYOffset
}
}
else if(document.compatMode == "CSS1Compat") // 声明的了 DTD
// 检测是不是怪异模式的浏览器 -- 就是没有 声明<!DOCTYPE html>
{
return {
left: document.documentElement.scrollLeft,
top: document.documentElement.scrollTop
}
} else {
return { // 剩下的肯定是怪异模式的
left: document.body.scrollLeft,
top: document.body.scrollTop
}
}

}

</script>
</html>

原生js实现缓动返回顶部

原文:http://www.cnblogs.com/chuanzhou/p/7468914.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!