DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS詳解
筆記:用 CSS Expression 修好 IE6 的 position:fixed
編輯:CSS詳解     

position:fixed 能讓元素固定在視窗的絕對位置,捲動捲軸也不會跑掉,是「回到頂端」按鈕、懸浮側邊欄的首選。問題是 IE6 完全不認這個屬性。以下把處理思路與可直接複用的程式碼片段整理出來。

標準寫法長什麼樣

position:fixed 生成的是相對瀏覽器視窗定位的物件,位置由 left、top、right、bottom 決定。以右下角的小按鈕為例:

#top{
  position: fixed;
  bottom: 0;
  right: 20px;
}

這段程式碼讓 <div id="top"> 固定在視窗底部、距右側 20px。

IE6 的對策:_ 前綴 hack

IE6 無法直接吃 position:fixed,必須靠 CSS hack 繞路。right 與 left 可以用絕對定位變通處理,top 與 bottom 則要靠 expression 動態計算:

#top{
  position: fixed;
  _position: absolute;
  bottom: 0;
  right: 20px;
  _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)));
}

關鍵在 _position: absolute; 中的下底線——只有 IE6 認得這個前綴,其他瀏覽器會直接跳過,因此不必額外寫條件式註解。

三個可直接複用的片段

固定在視窗頂部

#top{
  _position: absolute;
  _bottom: auto;
  _top: expression(eval(document.documentElement.scrollTop));
}

固定在視窗底部

#top{
  _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)));
}

微調位置

上面兩段只能貼齊最頂或最底,若要留一點間距,加上 _margin-top: 10px; 或 _margin-bottom: 10px; 調整數值即可。

還沒結束:閃動問題

套用上面的方法後會發現,滾動捲軸時被固定的元素會高速閃動。原因是 IE 的多段式渲染流程會在重繪時重新計算 expression,導致元素「追不上」捲動。解法是在 CSS 裡加一段:

* html{
  background-image: url(about:blank);
  background-attachment: fixed;
}

* html 這個選擇器只有 IE6 認得。加上 fixed 的背景附件後,IE 會被迫在重繪之前先處理 CSS,expression 的計算也就提前完成,閃動隨之消失。這裡不需要真實的圖片,about:blank 就夠用。

該不該繼續用這套寫法

expression 每次重繪都會執行一次 JavaScript,對效能有明顯傷害,在長頁面或低階裝置上容易卡頓。它屬於歷史包袱下的權宜之計——如果專案已不再需要支援 IE6,請直接使用原生的 position:fixed,別把這些程式碼帶進新專案。

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