<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>回到頂部scrollTop</title>
<style type="text/css">
#button{width: 50px;height: 50px;border-radius: 50%;background: #000;opacity: 0.4;position: fixed;bottom: 30px;right: 30px;display: none;}
.content{background:-webkit-gradient(linear, 0 0, 0 100%, from(green), to(yellow));height: 2000px;width: 100%;}
</style>
</head>
<body>
<div id="button"></div>
<div class="content"></div>
<script>
// 回到頂部scrollTop
// 總時間(duration):500ms
//頻率(interval):多長時間走一步 10ms
//總距離(target):當前的位置(當前的scrollTop值)目標位置0;
// 步長(step):每一次走的距離 target/duration * interval 每一次走的距離
var button = document.getElementById("button");
window.onscroll = computedDisplay;
function computedDisplay(){
var curTop = document.documentElement.scrollTop || document.body.scrollTop;
var curHeight = document.documentElement.clientHeight || document.body.clientHeight;
button.style.display = curTop>curHeight?"block":"none";
}
button.onclick = function(){
this.style.display = "none";
window.onscroll = null;
var duration = 500,interval = 10,target = document.documentElement.scrollTop || document.body.scrollTop;
var step = (target/duration) * interval;
var timer = window.setInterval(function(){
var curTop = document.documentElement.scrollTop || document.body.scrollTop;
if(curTop ===0){
window.clearInterval(timer);
window.onscroll = computedDisplay;//動畫結束后方法重新綁定
return;
}
curTop -=step;
document.documentElement.scrollTop = curTop;
document.body.scrollTop = curTop;
},interval);
}
</script>
</body>
</html>
js點擊按鈕滾動到頂部
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
- 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
- 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
- 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
推薦閱讀更多精彩內容
- <!DOCTYPE html> *{margin: 0;padding: 0;}.test{border...
- 只有一個ScrollView的時候 我們在使用App的時候,經常會看到這樣的效果,當我們點擊狀態欄的時候,我們已經...
- 背景 現在有許多 app 都有這個需求, 點擊 statusBar, tableView/collectionvi...