js簡單的點擊返回頂部效果實現方法,js返回頂部

來源:互聯網
上載者:User

js簡單的點擊返回頂部效果實現方法,js返回頂部

本文執行個體講述了js簡單的點擊返回頂部效果實現方法。分享給大家供大家參考。具體分析如下:

當頁面特別長的時候,使用者想回到頁面頂部,必須得滾動好幾次滾動鍵才能回到頂部,如果在頁面右下角有個“返回頂部”的按鈕,使用者點擊一下,就可以回到頂部,對於使用者來說,是一個比較好的體驗。

實現原理:當頁面載入的時候,把元素定位到頁面的右下角,當頁面滾動時,元素一直位於右下角,當使用者點擊的時候,頁面回到頂部。

要點一:document.documentElement.clientWidth || document.body.clientWidth; 獲得可視區的寬度。後面是相容chrome,前面是相容其它瀏覽器。

要點二:oTop.style.left = screenw - oTop.offsetWidth +"px";  當頁面載入時,讓元素的位置位於頁面最右邊,用可視區的寬度減去元素本身的寬度。

要點三:oTop.style.top = screenh - oTop.offsetHeight + scrolltop +"px"; 當頁面滾動時,元素的Y座標位置等於可視區的高度減去元素本身的高度,加上滾動距離。

要點四:document.documentElement.scrollTop = document.body.scrollTop =0; 當點擊元素時,讓頁面的滾動距離為0.寫兩個是為了相容。
 
上代碼:

<!DOCTYPE html><html><head><meta charset="utf-8" /><title>無標題文檔</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>

希望本文所述對大家的javascript程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.