本文示範如何監聽滾動條的滾動事件,讓某個元素相對於視窗維持在同一個位置。直接看程式碼最快。
<style>
#anchor:{
position:absolute;
top:40%;
left:40%;
width:100px;
height:100px;
background-color:red;
}
</style>
先在監聽器外部記錄元素初始的 top 位置,再在滾動時把初始值加上滾動量:
var anchorTop = $("#anchor").css("top");
anchorTop = Number(anchorTop.substring(0, anchorTop.indexOf("p"))); //記錄初始位置
window.onscroll = function () {
var top = document.documentElement.scrollTop || document.body.scrollTop;
$("#anchor").css("top", anchorTop + top + "px");
};
<div id="anchor"></div>
幾個關鍵點:document.documentElement.scrollTop || document.body.scrollTop 這種寫法是用來相容不同瀏覽器(Chrome 與 Firefox 支援的屬性不同),用 || 把兩者融合。另外,#anchor 必須設為 position:absolute,否則 top 值永遠是 0px。滾動時 top 值變化,把初始 top 加上滾動量,就能讓內容看起來始終停留在同一位置。