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(),用法完全對稱。