JS回到頂部按鈕實現原始碼
阿新 • • 發佈:2019-01-01
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> * { margin: 0; padding: 0; font-family: "微軟雅黑"; font-size: 14px; -webkit-user-select: none; } html, body { width: 100%; height: 500%; background: #11C900; /*css3背景顏色漸變效果*/ background: -webkit-linear-gradient(top, #11C900, lightgreen, lightblue, lightcoral, lightgoldenrodyellow, lightgoldenrodyellow, lightsalmon, lightseagreen, lightslategrey); background: linear-gradient(top, #11C900, lightgreen, lightblue, lightcoral, lightgoldenrodyellow, lightgoldenrodyellow, lightsalmon, lightseagreen, lightslategrey); } a { text-decoration: none; color: #000; } a:hover, a:active, a:target, a:visited { text-decoration: none; color: #000; } #goLink { display: none; position: fixed; /*說只要加了position,元素自己就變成了塊狀*/ bottom: 200px; right: 50px; width: 50px; height: 50px; line-height: 50px; text-align: center; background: red; border-radius: 50%; opacity: 0.2; filter: alpha(opacity=20); } #goLink:hover { opacity: 1; filter: alpha(opacity=100); } </style> </head> <body> <!--A標籤本身是跳轉頁面的,把跳轉的地址寫在href這個屬性中,不寫值的話是重新整理本頁面,寫了#xxx的話是錨點定位,定位到xxx處,寫成"javascript:;"是取消a標籤預設跳轉的行為--> <a href="javascript:;" id="goLink">Go</a> <script type="text/javascript"> var goLink = document.getElementById("goLink"); //回到頂部: //總時間(duration):500ms //頻率(interval):多長時間走一步 10ms //總距離(target):當前的位置(當前的scrollTop)-目標的位置(0) //步長(step):每一次走的距離 target/duration*interval //開始Go按鈕是不顯示,只有當瀏覽器捲去的高度超過一螢幕的高度的時候顯示,反之隱藏->只要瀏覽器的滾動條在滾動,我們就需要判斷GO顯示還是隱藏 //瀏覽器滾動條滾動:拖動滾動條、滑鼠滾輪、鍵盤上下鍵或者pageDown、pageUp、點選滾動條的空白處或者箭頭(自主操作行為)。。。我們還可通過js控制scrollTop的值實現滾動條的滾動 window.onscroll = computedDisplay; function computedDisplay() { var curTop = document.documentElement.scrollTop || document.body.scrollTop; var curHeight = document.documentElement.clientHeight || document.body.clientHeight; goLink.style.display = curTop > curHeight ? "block" : "none"; } goLink.onclick = function () { //當點選的時候讓當前的GO消失 this.style.display = "none";//光這樣還不行,我們往回走的時候又把window.onscroll的行為觸發了,讓go又顯示了->我們需要在點選後,把window.onscroll繫結的事件取消掉 window.onscroll = null; //當我點選go的時候,首先把每一步要走的步長計算出來 var duration = 500, interval = 10, target = document.documentElement.scrollTop || document.body.scrollTop; var step = (target / duration) * interval; //計算完成步長後,讓當前的頁面每隔interval這麼長的時間走一步:在上一次scrollTop的基礎上-步長 var timer = window.setInterval(function () { var curTop = document.documentElement.scrollTop || document.body.scrollTop; if (curTop === 0) {//已經到頭了 window.clearInterval(timer); window.onscroll = computedDisplay;//當動畫結束後還需要把對應的方法重新繫結為window.onscroll return; } curTop -= step; document.documentElement.scrollTop = curTop; document.body.scrollTop = curTop; }, interval) } </script> </body> </html>