可以先滾動頁面看看效果,再對照下面的說明。
$(window).scrollTop() // 目前垂直捲動的距離 $(document).scrollTop() // 同上,取得垂直捲動距離 $(document).scrollLeft() // 水平捲動條的距離
$(document).scrollTop() 的意義是「目前視窗頂端到整個頁面頂端的距離」。
$(document).height() // 整個頁面的完整高度 $(window).height() // 目前瀏覽器視窗可見部分的高度
這兩者很容易搞混。$(window).height() 會隨視窗縮放而改變,$(document).height() 則是內容的實際總長,與視窗大小無關。
到頂端:scrollTop() == 0。
到底端:scrollTop() >= $(document).height() - $(window).height()。
第二條式子的邏輯是「總高度減去視窗高度」等於最大可捲距離,一旦目前捲動量達到或超過它,就代表已經到底。這個判斷常用在無限滾動載入或顯示返回頂部按鈕的時機上。
<script>
$(document).scroll(function(){
$("#hovertreesc").text($(document).scrollTop());
})
</script>
<div id="hovertreesc" style="top:100px;left:100px;position:fixed;
width:50px;height:20px;background-color:silver;"></div>
這段程式把捲動距離即時寫進一個 position:fixed 的方塊裡,捲動時數字會持續變化。實務上若在 scroll 事件中做較重的運算,建議加上 throttle 或 requestAnimationFrame 來降低觸發頻率,避免影響流暢度。