DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS詳解
如何讓 position:fixed 在 IE6 中正常運作
編輯:CSS詳解     

眾所周知,IE6 不支援 position:fixed。這個 bug 與 IE6 的雙倍 margin、不支援 PNG 透明等問題一樣惡名昭彰。前些天我在製作自己的部落格模板時就遇到了它,當時便乾脆無視了 IE6——儘管身邊有幾個仍在使用 IE6 的朋友,一起吐槽我……但對於大型專案或商業網站而言,一旦用到了這個屬性,就不可能直接置之不理。

你是如何讓 position:fixed 在 IE6 中運作的?

本文所用的技巧,是借助了一條 Internet Explorer 的 CSS 運算式(expression)。你不能直接使用它,因為它可能因快取而無法更新。解決這個問題最簡單的方式,就是用 eval 包裹你的語句。

如何解決「振動」的問題?

顯然 IE 採用的是多步驟的渲染流程。當你捲動頁面或調整瀏覽器視窗大小時,它會重置內容並重繪頁面,此時便會重新處理 CSS 運算式。這會引起一個難看的「振動」bug:固定位置的元素需要調整以跟上捲動,於是就出現了「跳動」。

解決之道,是為 body 或 html 元素加上 background-attachment: fixed 並附上一個背景圖片。這會強迫頁面在重繪之前先處理 CSS;既然 CSS 在重繪前被處理,你的 CSS 運算式自然也會先在重繪前運算完成。如此一來,你就能實現完美平滑的固定定位效果!

這方案並非我原創,我是在網路上某處讀到的。如果你知道原作者,歡迎告訴我們。另外我還發現一個小技巧:你根本不需要一張真實的圖片!用 about:blank 來取代 spacer.gif,效果一樣出色。

CSS 程式碼

/* 讓 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 的部分移除。

注意:以上程式碼僅在標準模式下測試過。

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