當頁面過長時,一般會在頁面下方有一個返回頂部的button,總結一下,大概三種實現方法,下面說下各方法及優缺點。javascript
<a href="#" class="top" id="top">返回頂部</a>
這種方法設置方便,但缺點是會刷新頁面(我是在同事的樂視手機上發現的)。css
<a href="javascript:scrollTo(0,0)" class="top" id="top">返回頂部</a>
這種方法也很方便,而且不會刷新頁面,缺點是沒有滾動效果。
scrollTo接收的參數用來定位視口左上角在整個滾動內容區域的座標,好比我設置scrollTo(100,100),就是讓滾動內容的座標(100,100)的點處在視口的左上角。html
/* html部分 */ <body> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <a href="javascript:;" class="top" id="top">返回頂部</a> </body>
<style> /* css部分 */ div { height: 150px; } div:nth-child(odd) { background-color: #8ae238; } div:nth-child(even) { background-color: #66d9ef; } .top { position: fixed; right: 50px; bottom: 50px; display: block; width: 50px; height: 50px; font-size: 20px; background-color: white; display: none; } </style>
<script> /* js代碼 */ var topBtn = document.getElementById('top'); // 獲取視窗高度 var winHeight = document.documentElement.clientHeight; window.onscroll = function () { // 獲取頁面向上滾動距離,chrome瀏覽器識別document.body.scrollTop,而火狐識別document.documentElement.scrollTop,這裏作了兼容處理 var toTop = document.documentElement.scrollTop || document.body.scrollTop; // 若是滾動超過一屏,返回頂部按鈕出現,反之隱藏 if(toTop>=winHeight){ topBtn.style.display = 'block'; }else { topBtn.style.display = 'none'; } } topBtn.onclick=function () { var timer = setInterval(function () { var toTop = document.documentElement.scrollTop || document.body.scrollTop; // 判斷是否到達頂部,到達頂部中止滾動,沒到達頂部繼續滾動 if(toTop == 0){ clearInterval(timer); }else { // 設置滾動速度 var speed = Math.ceil(toTop/5); // 頁面向上滾動 document.documentElement.scrollTop=document.body.scrollTop=toTop-speed; } },50); } </script>
大概的思路就是:java
jQuery方法只是在js代碼部分不一樣,具體代碼以下jquery
<script> /* js代碼 */ $(window).on('scroll', function () { // 判斷顯示仍是隱藏按鈕 if($(this).scrollTop()>=$(this).height()){ $('#top').fadeIn('slow'); }else { $('#top').fadeOut('slow'); } }); $('#top').on('click',function () { // 設置滾動動畫,這裏注意使用的是$('body')不是$(window) $('body').animate({scrollTop:'0'},500); }); </script>
jQuery方法的優勢是方便,並且動畫效果比較流暢。
這裏須要注意設置animate方法時使用的是jQuery封裝的body對象而不是window對象,由於咱們是要設置body的scrollTop屬性。chrome
三個方法各有優劣,不過整體來說,jQuery的方法更適合大多數場景。瀏覽器
https://www.zybuluo.com/EncyKe/note/254250
http://www.cnblogs.com/mind/archive/2012/03/23/2411939.html動畫