<!DOCTYPE html>
<html> <head> <meta charset="UTF-8"> <title>回到頂部</title> <style> * { margin: 0; padding: 0; } html, body { height: 1000%; background: -webkit-linear-gradient(top left, lightblue, lightpink, lightyellow); } .link { display: none; position: fixed; right: 30px; bottom: 230px; box-sizing: border-box; width: 100px; height: 100px; background: lightcoral; font-size: 16px; color: #000; text-decoration: none; text-align: center; line-height: 100px; } </style> </head> <body> <a href="javascript:;" id="link" class="link">回到頂部</a> <script> let HTML = document.documentElement, LINK = document.getElementById('link'); function check() { let winH = HTML.clientHeight, scrollT = HTML.scrollTop; LINK.style.display = scrollT >= winH * 2 ? 'block' : 'none'; } window.onscroll = check; LINK.onclick = function () { LINK.style.display = 'none'; window.onscroll = null; let step = 1000; let timer = setInterval(() => { let curT = HTML.scrollTop; if (curT === 0) { clearInterval(timer); window.onscroll = check; return; } curT -= step; HTML.scrollTop = curT; }, 17); }; </script> </body> </html> 複製代碼