#### 1. 背景介紹 --- 當(dāng)頁面內(nèi)容很多的時候,用戶可能會一直往下滑動頁面。但是當(dāng)他想返回頁面頂部進行其他操作時,他可能需要不斷滾動鼠標(biāo)滾輪,這就導(dǎo)致用戶體驗將很差。鑒于這種情況, “回到頂部”這一功能便出現(xiàn)了。 #### 2. 返回頂部代碼示例 --- ```html <style> div.box { height: 1000px; background-color: aqua; margin-bottom: 20px; } div#gotop { width: 30px; height: 30px; cursor: pointer; border-radius: 4px; background-color: #4c4c4c; position: fixed; right: 30px; bottom: 60px; } div#gotop img { width: 100%; height: 100%; } </style> <div class="box"></div> <div class="box"></div> <div id="gotop"> <img src="http://beautifulforever.com.cn/static/index/plugin/fixed/images/top.png"> </div> <script> window.onscroll = () => { const res = document.body.scrollTop || document.documentElement.scrollTop const gotop = document.getElementById('gotop') gotop.style.display = res > 400 ? 'block' : 'none' } gotop.onclick = () => { let res = document.body.scrollTop || document.documentElement.scrollTop let t = res / 60 const index = setInterval(() => { res -= t if (res < 0) { res = 0 clearInterval(index) } document.body.scrollTop = res document.documentElement.scrollTop = res }, 5); } </script> ```