js簡單的點(diǎn)擊返回頂部效果實(shí)現(xiàn)方法

字號:


    當(dāng)頁面特別長的時候,用戶想回到頁面頂部,必須得滾動好幾次滾動鍵才能回到頂部,如果在頁面右下角有個“返回頂部”的按鈕,用戶點(diǎn)擊一下,就可以回到頂部,對于用戶來說,是一個比較好的體驗(yàn)。
    實(shí)現(xiàn)原理:當(dāng)頁面加載的時候,把元素定位到頁面的右下角,當(dāng)頁面滾動時,元素一直位于右下角,當(dāng)用戶點(diǎn)擊的時候,頁面回到頂部。
    要點(diǎn)一:document.documentElement.clientWidth || document.body.clientWidth; 獲得可視區(qū)的寬度。后面是兼容chrome,前面是兼容其它瀏覽器。
    要點(diǎn)二:oTop.style.left = screenw - oTop.offsetWidth +"px"; 當(dāng)頁面加載時,讓元素的位置位于頁面最右邊,用可視區(qū)的寬度減去元素本身的寬度。
    要點(diǎn)三:oTop.style.top = screenh - oTop.offsetHeight + scrolltop +"px"; 當(dāng)頁面滾動時,元素的Y坐標(biāo)位置等于可視區(qū)的高度減去元素本身的高度,加上滾動距離。
    要點(diǎn)四:document.documentElement.scrollTop = document.body.scrollTop =0; 當(dāng)點(diǎn)擊元素時,讓頁面的滾動距離為0.寫兩個是為了兼容。
    上代碼:
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8" />
    <title>無標(biāo)題文檔</title>
    <style>
    body{margin:0; padding:0}
    #to_top{width:30px; height:40px; padding:20px; font:14px/20px arial; text-align:center; background:#06c; position:absolute; cursor:pointer; color:#fff}
    </style>
    <script>
    window.onload = function(){
    var oTop = document.getElementById("to_top");
    var screenw = document.documentElement.clientWidth || document.body.clientWidth;
    var screenh = document.documentElement.clientHeight || document.body.clientHeight;
    oTop.style.left = screenw - oTop.offsetWidth +"px";
    oTop.style.top = screenh - oTop.offsetHeight + "px";
    window.onscroll = function(){
    var scrolltop = document.documentElement.scrollTop || document.body.scrollTop;
    oTop.style.top = screenh - oTop.offsetHeight + scrolltop +"px";
    }
    oTop.onclick = function(){
    document.documentElement.scrollTop = document.body.scrollTop =0;
    }
    }
    </script>
    </head>
    <body>
    <h1>返回頂部</h1>
    <div id="to_top">返回頂部</div>
    </body>
    </html>