DIV CSS 佈局教程網

用 JavaScript 製作固定在右下角的返回頂部按鈕
編輯:JavaScript綜合知識     

博客頁右下角那個無論怎麼滾動都稳稳待在原地的「回到頂部」小圖標,實現起來只有兩個知識點:CSS 固定定位,加上一個定時滾動的 JS 函數。

一、讓按鈕固定

CSS 的 position 有五種取值,這裡要的是 fixed——它相對瀏覽器窗口定位,不隨頁面滾動而移動,正好符合需求:

absolute  相對 static 以外的第一個父元素定位
fixed     相對浏覽器窗口定位,位置由 left/top/right/bottom 決定
relative  相對自身正常位置定位,如 left:20 表示向右偏移 20 像素
static    默認值,元素處於正常文檔流中,top/left 等聲明被忽略
inherit   從父元素繼承 position 的取值
#myTopBtn{
  bottom: 5px;
  right: 5px;
  position: fixed;
}

二、控制滾動條移動

JS 提供了兩個相關方法:

window.scrollBy(0, -30)  // 向上滾動 30 像素
window.scroll(0, 0)      // 直接回到左上角

要實現「平滑滑上去」而不是瞬移,就需要用 setInterval 反覆調用 scrollBy,每 10 毫秒上移一點,直到抵達頂部後清除定時器:

var myVar;
function TopFunc(){
  myVar = setInterval(EachScrollBy, 10);
}

function EachScrollBy(){
  if(document.documentElement.scrollTop <= 0){
    clearInterval(myVar);
  } else {
    window.scrollBy(0, -30);
  }
}

配套的結構很簡單:

<button id="myTopBtn" onclick="TopFunc()">To Top</button>

三、擴展:實現置底

原理完全一樣,只是判斷條件換成「是否已到達底部」。這裡整理一批常用尺寸屬性備查:

網頁可見區域寬:document.body.clientWidth
網頁可見區域高:document.body.clientHeight
網頁可見區域寬(含邊線):document.body.offsetWidth
網頁可見區域高(含邊線):document.body.offsetHeight
網頁正文全文寬:document.body.scrollWidth
網頁正文全文高:document.body.scrollHeight
網頁被卷去的高:document.body.scrollTop
網頁被卷去的左:document.body.scrollLeft
網頁正文部分上:window.screenTop
網頁正文部分左:window.screenLeft
屏幕分辨率的高:window.screen.height
屏幕分辨率的寬:window.screen.width
屏幕可用工作區高:window.screen.availHeight
屏幕可用工作區寬:window.screen.availWidth

最後提一句:現代項目裡,返回頂部可以直接用 window.scrollTo({top:0, behavior:'smooth'}),瀏覽器原生就支持平滑滾動,不必自己寫定時器;按鈕的顯示隱藏也可以監聽 scroll 事件配合 class 切換來做。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved