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

字號(hào):


    當(dāng)頁(yè)面特別長(zhǎng)的時(shí)候,用戶(hù)想回到頁(yè)面頂部,必須得滾動(dòng)好幾次滾動(dòng)鍵才能回到頂部,如果在頁(yè)面右下角有個(gè)“返回頂部”的按鈕,用戶(hù)點(diǎn)擊一下,就可以回到頂部,對(duì)于用戶(hù)來(lái)說(shuō),是一個(gè)比較好的體驗(yàn)。
    實(shí)現(xiàn)原理:當(dāng)頁(yè)面加載的時(shí)候,把元素定位到頁(yè)面的右下角,當(dāng)頁(yè)面滾動(dòng)時(shí),元素一直位于右下角,當(dāng)用戶(hù)點(diǎn)擊的時(shí)候,頁(yè)面回到頂部。
    要點(diǎn)一:document.documentelement.clientwidth || document.body.clientwidth; 獲得可視區(qū)的寬度。后面是兼容chrome,前面是兼容其它瀏覽器。
    要點(diǎn)二:otop.style.left = screenw - otop.offsetwidth +px; 當(dāng)頁(yè)面加載時(shí),讓元素的位置位于頁(yè)面最右邊,用可視區(qū)的寬度減去元素本身的寬度。
    要點(diǎn)三:otop.style.top = screenh - otop.offsetheight + scrolltop +px; 當(dāng)頁(yè)面滾動(dòng)時(shí),元素的y坐標(biāo)位置等于可視區(qū)的高度減去元素本身的高度,加上滾動(dòng)距離。
    要點(diǎn)四:document.documentelement.scrolltop = document.body.scrolltop =0; 當(dāng)點(diǎn)擊元素時(shí),讓頁(yè)面的滾動(dòng)距離為0.寫(xiě)兩個(gè)是為了兼容。
    上代碼:
    <!doctype html>
    <html>
    <head>
    <meta charset=utf-8 />
    <title>無(wú)標(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 style=height:1000px;>
    <h1>返回頂部</h1>
    <div id=to_top>返回頂部</div>
    </body>
    </html>