DIV CSS 佈局教程網

滾動超過門檻就轉為固定定位:jQuery 實作「黏」住的側欄
編輯:JQuery特效代碼     

向下捲動頁面時,某個區塊(例如側邊欄、篩選器、工具列)會黏在視窗上方持續可見——淘寶的產品列表與騰訊財經的產業經濟頁都是這個模式,是很值得學的用戶體驗細節。

淘寶產品列表:
https://search1.taobao.com/browse/50010388/…

騰訊財經產業經濟:
https://finance.qq.com/industry/index.htm

先搞懂 scrollTop 是什麼

當元素內容高度超過元素本身高度時會出現滾動條;被捲走、隱藏在上方的那段高度值,就是 scrollTop。

而所謂「定位層」的做法其實很直白:頁面觸發 onscroll 時讀取 scrollTop,把它寫進定位層的 CSS 屬性,讓這個區塊在視覺上維持在同一個位置。

實作程式碼

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>定位層</title>
<script type="text/javascript" src="https://img.poluoluo.com/jslib/jquery/jquery.js"></script>

<style type="text/css">
body { padding: 10px; margin: 0; }
#box  { width: 960px; margin: 0 auto; }
#box1 { width: 250px; height: 25px; position: relative; }
#box1_1 {
    width: 250px; height: 25px; line-height: 25px;
    background: #f00; color: #fff;
}
p { font-size: 24px; margin: 10px 0; }
</style>

<script type="text/javascript">
function tools() {
    var top = $(document).scrollTop();
    if ( ($.browser.msie == true) && ($.browser.version == 6.0) ) {
        // IE6 不支援 position:fixed,改用 absolute 加上補償值模擬
        if (top > 168) { $("#box1_1").css({ position: "absolute", top: top - 168 }); }
    } else {
        if (top > 168) { $("#box1_1").css({ position: "fixed", top: "-" + top + "px" }); }
    }
    if (top <= 168) { $("#box1_1").css({ position: "static", top: 0 }); }
}

$(function () {
    window.onscroll  = tools;
    window.onresize = tools;
});
</script>
</head>

<body>
<div id="box">
  <p>往下拖動滾動條↓ <a href="https://www.poluoluo.com">poluoluo.com</a></p>
  <!-- 這裡放入足够高的內容以便產生滾動 -->
  <p><a href="https://www.poluoluo.com">poluoluo.com</a> ...</p>

  <div id="box1">
    <div id="box1_1">這裡是定位層</div>
  </div>

  <p><a href="https://www.poluoluo.com">poluoluo.com</a> ...</p>
</div>
</body>
</html>

三個實作要點

門檻值判斷。範例用 168px 當切換點,實務上應該用 $("#box1").offset().top 動態計算,寫死數字在版面調整後就會失效。

IE6 的無奈。IE6 不認 position: fixed,只能用 absolute 搭配手動補償 scroll 值來模擬。今天若還要支援 IE6,建議改用滾動時的 rAF 節流來降低重排成本。

記得綁 onresize。視窗尺寸改變時元素的 offset().top 也會變,少了 resize 監聽,切換門檻就會算錯。另外把 onscroll 換成 $('#box1') 的 scroll 事件並加上節流,效能會好很多。

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