前端-回到顶部效果总结
1.錨點:
使用錨點鏈接是一種簡單的返回頂部的功能實現。該實現主要在頁面頂部放置一個指定名稱的錨點鏈接,然后在頁面下方放置一個返回到該錨點的鏈接,用戶點擊該鏈接即可返回到該錨點所在的頂部位置。
<body style="height:2000px;"><div id="topAnchor"></div><a href="#topAnchor" style="position:fixed;right:0;bottom:0">回到頂部</a> </body>2.scrollTop
scrollTop屬性表示被隱藏在內容區域上方的像素數。元素未滾動時,scrollTop的值為0,如果元素被垂直滾動了,scrollTop的值大于0,且表示元素上方不可見內容的像素寬度。
由于scrollTop是可寫的,可以利用scrollTop來實現回到頂部的功能。另外注意關于頁面的scrollTop的兼容問題。
<body style="height:2000px;"><button id="test" style="position:fixed;right:0;bottom:0">回到頂部</button><script>test.onclick = function(){document.body.scrollTop = document.documentElement.scrollTop = 0;}</script> </body>3.scrollTo()
scrollTo(x,y)方法滾動當前window中顯示的文檔,讓文檔中由坐標x和y指定的點位于顯示區域的左上角。設置scrollTo(0,0)可以實現回到頂部的效果。
<body style="height:2000px;"><button id="test" style="position:fixed;right:0;bottom:0">回到頂部</button><script>test.onclick = function(){scrollTo(0,0);}</script> </body>4.scrollBy()
scrollBy(x,y)方法滾動當前window中顯示的文檔,x和y指定滾動的相對量。
只要把當前頁面的滾動長度作為參數,逆向滾動,則可以實現回到頂部的效果。
<body style="height:2000px;"><button id="test" style="position:fixed;right:0;bottom:0">回到頂部</button><script>test.onclick = function(){var top = document.body.scrollTop || document.documentElement.scrollTopscrollBy(0,-top);}</script> </body>5.scrollIntoView()
Element.scrollIntoView方法滾動當前元素,進入瀏覽器的可見區域
該方法可以接受一個布爾值作為參數。如果為true,表示元素的頂部與當前區域的可見部分的頂部對齊(前提是當前區域可滾動);如果為false,表示元素的底部與當前區域的可見部分的尾部對齊(前提是當前區域可滾動)。如果沒有提供該參數,默認為true
使用該方法的原理與使用錨點的原理類似,在頁面最上方設置目標元素,當頁面滾動時,目標元素被滾動到頁面區域以外,點擊回到頂部按鈕,使目標元素重新回到原來位置,則達到預期效果
<body style="height:2000px;"><div id="target"></div><button id="test" style="position:fixed;right:0;bottom:0">回到頂部</button><script>test.onclick = function(){target.scrollIntoView();}</script> </body>增加scrollTop的動畫效果
使用定時器requestAnimationFrame,將scrollTop的值每次減少50,直到減少到0,則動畫完畢。IE9-瀏覽器不支持該方法,可以使用setTimeout來兼容
<script> var timer = null; box.onclick = function(){cancelAnimationFrame(timer);//清除定時器timer = requestAnimationFrame(function fn(){var oTop = document.body.scrollTop || document.documentElement.scrollTop;if(oTop > 0){document.body.scrollTop = document.documentElement.scrollTop = oTop - 50;timer = requestAnimationFrame(fn);}else{cancelAnimationFrame(timer);//清除定時器} }); } </script>由快到慢動畫效果,體驗較好:
原理:因為減過之后的scrollTop越來越少,減的值越來越少,給人一種由快到慢的感覺。因為document.body.scrollTop與document.documentElement.scrollTop只會有一個有值,所以需要判斷一下,最后回到頂部后,清除掉定時器。speed可以設置大小,除數越大speed值越小,動畫效果越慢。
scrollToptimer = setInterval(function () {console.log("定時循環回到頂部")var top = document.body.scrollTop || document.documentElement.scrollTop;var speed = top / 4;if (document.body.scrollTop!=0) {document.body.scrollTop -= speed;}else {document.documentElement.scrollTop -= speed;}if (top == 0) {clearInterval(scrollToptimer);} }, 30);總結
以上是生活随笔為你收集整理的前端-回到顶部效果总结的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Vijos1986
- 下一篇: 2017年html5行业报告,云适配发布