頁面側邊欄模塊隨頁面滾動,當滾動到頂部時自動固定頂部 (position: fixed),向下滾動超過原始位置恢復靜態定位,不遮擋頂部導航。
(function() {
const floatEl = document.getElementById("float");
if (!floatEl) return;
// 計算元素初始距離文檔頂部的偏移量
let offsetTop = 0;
let el = floatEl;
while (el) {
offsetTop += el.offsetTop;
el = el.offsetParent;
}
// 檢測 IE6 (可選,現代專案可移除)
const isIE6 = window.ActiveXObject && !window.XMLHttpRequest;
window.addEventListener("scroll", function() {
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
if (scrollTop > offsetTop) {
// 超過原始位置:固定頂部
floatEl.className = "div1 div2"; // 添加 fixed class
if (isIE6) {
floatEl.style.top = (scrollTop - offsetTop) + "px"; // IE6 模擬 fixed
}
} else {
// 回到原位:靜態定位
floatEl.className = "div1";
}
});
})();
<div id="box" class="sidebar-container">
<div id="float" class="div1">
<!-- 這裡放需要浮動的內容:廣告、導航、客服等 -->
<h3>熱門推薦</h3>
<ul><li>商品 1</li><li>商品 2</li></ul>
</div>
</div>
/* 容器:建立定位上下文 */
#box {
float: left;
position: relative; /* 關鍵:fixed 相對最近的定位祖先,這裡讓 fixed 相對視口 */
width: 295px;
}
/* 靜態狀態:正常文檔流 */
.div1 {
/* 無特殊定位,跟隨文檔流 */
}
/* 固定狀態:吸頂 */
.div2 {
position: fixed;
_position: absolute; /* IE6 hack */
top: 3px; /* 距離視口頂部間距 */
z-index: 295; // 確保層級足夠高
}
/* IE6 專用:模擬 fixed (需 JS 動態設定 top) */
* html .div2 {
position: absolute;
}
offsetParent 向上遍歷至 body,獲取元素相對文檔的真實位置,而非相對父容器.div1.div2 選擇器優先級高於 .div1_position: absolute + JS 動態計算 top 模擬 fixed,現代專案可完全移除scroll 事件高頻觸發,建議加 防抖/節流 或用 IntersectionObserver 現代方案/* CSS 單行搞定 (現代瀏覽器全支援) */
#float {
position: sticky;
top: 10px; /* 距離視口頂部 10px 吸附 */
z-index: 100;
}
/* 無需任何 JavaScript! */
position: sticky 兼容性:Chrome 56+、Firefox 32+、Safari 6.1+、Edge 16+。IE 全系不支援,需 Polyfill 或降級方案。
offsetTop 計算會在內容未渲染時執行,導致位置錯誤#box 需 position: relative 建立定位上下文offsetTop 或改用 sticky