DIV CSS 佈局教程網

jQuery scrollTop() 方法詳解:讀取與設定垂直捲動位置
編輯:JQuery特效代碼     

scrollTop() 用來取得或設定符合元素垂直捲軸的偏移量。它有一個很實用的特性:同一個方法名,帶不帶參數就分別對應「讀」與「寫」兩種行為。

語法一:不帶參數——取得捲動量

$(selector).scrollTop()

回傳符合元素相對於捲軸頂部的偏移量,單位為像素。

實作範例

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>scrollTop() 函數</title>
<style type="text/css">
  #div1 { border:1px solid black; width:200px; height:200px; overflow:auto }
  #div2 { height:250px; }
  #div3 { height:48px; width:30px; border:1px solid red; }
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
  $(document).ready(function(){
    $("button").click(function(){
      alert($("#div1").scrollTop() + " px");
    });
  });
</script>
</head>
<body>
  <div id="div1">
    <div id="div2">
      <div id="div3"></div>
    </div>
  </div>
  <button>取得捲動值</button>
</body>
</html>

由於 div2 高 250px 而容器 div1 只有 200px 且設了 overflow:auto,垂直捲軸會出現,此時 scrollTop() 才有有意義的返回值。

語法二:帶參數——設定捲動位置

$(selector).scrollTop(val)

參數 val 為要設定的垂直捲軸值。

實作範例

<script type="text/javascript">
  $(document).ready(function(){
    $("button").click(function(){
      $("#div1").scrollTop(30);
    });
  });
</script>

實務應用

最常見的用法是「回到頂端」按鈕:$(window).scrollTop(0) 或搭配 $("html,body").animate({scrollTop:0}) 做出平滑滾動。另一個常見場景是無限捲動——在 scroll 事件中比對 $(document).scrollTop() + $(window).height() 與文件總高,判斷是否該載入下一批資料。

對應的水平版本是 scrollLeft(),用法完全對稱。

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