標籤:document 垂直 math 改變 onscroll lock 檢測 隱藏 其他
<!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實現緩動返回頂部