原生态js回顶部
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" /> <title>Document</title> <style type="text/css"> * { margin: 0; padding: 0; } .public_gotop { background-color: #858585; position: fixed; right: 2rem; bottom: 6rem; width: 3rem; height: 3rem; border-radius: 50%; background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAABN0lEQVRYhe3Uuy4FURjFcZEjiMu76FwLiWuLhJJ4FU+gFwqNa1SuHQmtzhNoJRxB3H4Kc+LLGJdzDI1Z3cxe3/qvvfdk6uoKFSpUqEahFetYRtNfw9tx4k2HaPkreBuOvdcBmn8b3pyAKrrCTXjeQsNvwVtxFGAX6EAPyuH9bu7fRMbOL9EZ1ntTJbbRmBe8CfupY+/K8A2krmPzx9eRwPdS8O5P/IO4Df4NlGqFN2InhJXR+425oVSJtapLJPDtEHKNvirmR3AX5le+XQINydFVdIOBqnbwmjOaKrGE+q+GSl5/rxXdYqhaeMgbw33IW/ywRAJfTcGHa4WH3HE8hNyFzBKYD6YHTPwUHrKn8RTy57JM58niIybzgof8WTwnjLMsQz9OMZU3PDBmEkbn1+5ChQr9F70Ae6lHrD/JbEkAAAAASUVORK5CYII=); background-repeat: no-repeat; background-position: center; background-size: 60%; display: none; } </style> </head> <body> <div style="height: 500px; background: #E1A0F3"></div> <div style="height: 500px; background: #CE77B5"></div> <div class="public_gotop" id="gotop"></div> <script type="text/javascript"> window.onload = function() { // 返回顶部 var goTopEx = function() { var gtObj = document.getElementById("gotop"); function getScrollTop() { return document.documentElement.scrollTop || document.body.scrollTop; } function setScrollTop(value) { document.documentElement.scrollTop = value; document.body.scrollTop = value; } window.onscroll = function() { getScrollTop() > 80 ? gtObj.style.display = "block" : gtObj.style.display = "none"; } gtObj.onclick = function() { var goTop = setInterval(scrollMove, 10); function scrollMove() { setScrollTop(getScrollTop() / 1.1); if (getScrollTop() < 1) clearInterval(goTop); } } }() } </script> </body> </html>
效果如图:
备注解释:
function goTopEx() { //函数名goToEx var obj = document.getElementById("goTopBtn"); //获取id为goTopBtn的元素 function getScrollTop() { //函数名为getScrollTop return document.documentElement.scrollTop; //返回document.documentElement(html)的滚动条的高度 } function setScrollTop(value) { //函数名为setScrollTop,形参为value document.documentElement.scrollTop = value; //设置document.documentElement(html)的滚动条的高度为value } window.onscroll = function() { getScrollTop() > 0 ? obj.style.display = "" : obj.style.display = "none"; }; //当移动鼠标的时候,如果document.documentElement(html)的滚动条的高度>0,则obj显示,否则隐藏掉 obj.onclick = function() { //点击obj var goTop = setInterval(scrollMove, 10); //每隔10毫秒发生scroolMove方法 function scrollMove() { //函数名为scrollMove setScrollTop(getScrollTop() / 1.1); //设置document.documentElement(html)的滚动条的高度为getScrollTop()/1.1 if (getScrollTop() < 1) clearInterval(goTop); //如果得到document.documentElement(html)的滚动条的高度<1,则清除掉scroolMove方法 } }; }