解決 IE6 position:fixed 固定定位問題

關於 position:fixed; 屬性
生成絕對定位的元素,相對於瀏覽器窗口進行定位。
元素的位置通過 “left”, “top”, “right” 以及 “bottom” 屬性進行規定。
position:fixed; 可以讓網頁上的某個元素固定在一個絕對的位置,即使拉動滾動條位置也不發生變化。(在 LOO2K 博客右下角的那個置頂的小按鈕就是用了這個 CSS 屬性實現的)
一般的 position:fixed; 實現方法
以我的博客為例,在右下角<div id="top">...</div>
這個 HTML 元素使用的 CSS 代碼如下:
#top{ position:fixed; bottom:0; right:20px;}
實現讓<div id="top">...</div>
元素固定在瀏覽器的底部和距離右邊的20個像素。
在 IE6 中實現 position:fixed; 的辦法
剛剛提過,在 IE6 中是不能直接使用 position:fixed; 。你需要一些 CSS Hack 來解決它。(當然,IE6 的問題也不僅僅 position:fixed;)
相同的還是讓 <div id="top">...</div>
元素固定在瀏覽器的底部和距離右邊的20個像素,這次的代碼是:
#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)));}
right 跟 left 屬性可以用絕對定位的辦法解決,而 top 跟 bottom 就需要用上面的表達式來實現。其中在_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;
修改其中的數值控制元素的位置。
position:fixed; 閃動問題
現在,問題還沒有完全解決。在用了上面的辦法后,你會發現:被固定定位的元素在滾動滾動條的時候會閃動。解決閃動問題的辦法是在 CSS 文件中加入:
*html{ background-image:url(about:blank); background-attachment:fixed;}
其中 *
是給 IE6 識別的。
到此,IE6 的 position:fixed; 問題已經被解決了。現在 LOO2K 這個博客上的固定定位就是使用的這個辦法解決 IE6 固定定位問題的。