原生js實現緩動返回頂部

來源:互聯網
上載者:User

標籤: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實現緩動返回頂部

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.