DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS詳解
讓 position:fixed 在 IE6 中真正可用的完整寫法
編輯:CSS詳解     

IE6 不支援 position:fixed,這個 bug 和「雙倍 margin」、「PNG 不透明」一樣惡名昭彰。做個人部落格時可以乾脆無視它,但如果是商業網站或大型專案,這個屬性用在懸浮按鈕、固定側欄上幾乎無法迴避。以下是一套可直接複用的解法。

核心原理:CSS Expression

做法是用 IE 專屬的 CSS 表達式(expression)動態計算位置。但不能直接把 expression 寫上去就完事——它會因為快取而不更新,捲動時元素完全不動。最簡單的解法是用 eval 把整段敘述包起來,強制每次重算。

順手解決「抖動」bug

IE 採用多段式渲染流程:當你捲動或改變視窗大小,它會重置內容並重畫頁面,此時才重新處理 CSS 表達式。這段時間差就是抖動的來源——固定元素來不及跟上捲動,看起來像在跳。

解法是幫 body 或 html 加上 background-attachment: fixed 的背景圖。這會強迫 IE 在重繪「之前」先處理 CSS;既然 CSS 提前處理,expression 自然也提前算完,固定元素就能完美貼合。

更妙的是,你根本不需要真實的圖片檔,用 about:blank 代替 spacer.gif 效果完全一樣。

完整程式碼

/* 讓 position:fixed 在 IE6 下可用 */

.fixed-top    /* 頭部固定 */ { position: fixed; bottom: auto; top: 0px; }
.fixed-bottom /* 底部固定 */ { position: fixed; bottom: 0px;  top: auto; }
.fixed-left   /* 左側固定 */ { position: fixed; right: auto; left: 0px; }
.fixed-right  /* 右側固定 */ { position: fixed; right: 0px;  left: auto; }

/* 以上是除 IE6 以外主流瀏覽器通用的寫法 */

* html, * html body /* 修正 IE6 抖動 bug */ {
  background-image: url(about:blank);
  background-attachment: fixed;
}

* html .fixed-top /* IE6 頭部固定 */ {
  position: absolute;
  bottom: auto;
  top: expression(eval(document.documentElement.scrollTop));
}

* html .fixed-right /* IE6 右側固定 */ {
  position: absolute;
  right: auto;
  left: expression(eval(
    document.documentElement.scrollLeft
    + document.documentElement.clientWidth - this.offsetWidth
    - (parseInt(this.currentStyle.marginLeft, 10) || 0)
    - (parseInt(this.currentStyle.marginRight, 10) || 0)));
}

* html .fixed-bottom /* IE6 底部固定 */ {
  position: absolute;
  bottom: auto;
  top: expression(eval(
    document.documentElement.scrollTop
    + document.documentElement.clientHeight - this.offsetHeight
    - (parseInt(this.currentStyle.marginTop, 10) || 0)
    - (parseInt(this.currentStyle.marginBottom, 10) || 0)));
}

* html .fixed-left /* IE6 左側固定 */ {
  position: absolute;
  right: auto;
  left: expression(eval(document.documentElement.scrollLeft));
}

使用說明

這份寫法已加入 border、padding 與 margin 的支援。如果你確定不需要處理 margin,可以把所有 parseInt 的段落刪掉,expression 會短很多,效能也略好。

注意:以上程式碼只在標準模式(standards mode)下測試過。若頁面跑在 quirks mode,document.documentElement.clientHeight 會取到錯誤的值,需改用 document.body.clientHeight。

效能上的坦白話

每個 expression 都是一段會被反覆執行的 JavaScript。同一頁面上掛越多個固定元素,捲動就越卡。實務建議:IE6 專用樣式獨立成一份檔案、用條件式註解載入,並把固定元素數量壓到一個以內;或直接對 IE6 使用者提供「不固定」的降級版本。

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