DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS進階教程
讓 position:fixed 在 IE6 中完美生效的實戰技巧
編輯:CSS進階教程     

說到 IE6 的兼容性問題,不支持 position:fixed 絕對能排進那份臭名昭著的清單,與雙倍 margin、PNG 透明等經典 bug 齊名。前些日子筆者在製作自己的部落格模板時就撞上了這個難題,當時圖省事直接無視了 IE6——儘管身邊有幾個仍在使用 IE6 的朋友為此「抗議」了一番。但對於大型專案或商業網站而言,一旦用到了這個屬性,就無法再視而不見了。

核心思路:巧用 CSS 表達式

本文所用技巧依托的是 Internet Explorer 的一條 CSS 表達式(expression)。需要注意的是,你不能直接使用該表達式,因為它可能因緩存而無法即時更新。最簡單的解法是用 eval 包裹你的語句,強迫瀏覽器重新計算。

如何消除「振動」難題?

IE 採用的是多步渲染進程。當你滾動頁面或調整窗口大小時,它會重置並重繪所有內容,這個過程中 CSS 表達式會被重新處理。於是固定定位的元素需要不斷調整位置以追上滾動,便產生了令人頭疼的「跳動」或「振動」bug。

破解之道同樣巧妙:為 body 或 html 元素添加一個 background-attachment:fixed 的背景圖像。這會強迫頁面在重繪之前先行處理 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