position:fixed 能讓元素固定在視窗上、捲動時不動如山,可惜 IE6 完全不認這個屬性。在還需要支援 IE6 的年代,工程師得繞路實現。以下記錄兩種常見做法與各自的坑。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>IE6 position:fixed bug</title>
<style>
*{padding:0;margin:0}
p{height:2000px}
#gs{border:1px solid #000;position:fixed;right:30px;top:120px}
</style>
<!--[if IE 6]>
<style type="text/css">
html{overflow:hidden}
body{height:100%;overflow:auto}
#gs{position:absolute}
</style>
<![endif]-->
</head>
<body>
<div id="rightform">
<p>內容撐高頁面</p>
<input id="gs" name="gs" type="text" value="" />
</div>
</body>
</html>
原理是把捲軸從 html 移到 body 上,讓 body 成為滾動容器,其中的 absolute 元素自然就「固定」了。這個做法網路上到處可見,但有個明顯缺陷:頁面上原本所有 position:absolute 的元素都會一起變成 fixed 的行為,如果你的版面用到了絕對定位,就會全盤錯亂。
另一條路是利用 IE 專屬的 CSS 表達式(expression),讓元素位置持續貼合捲動量:
/* 除IE6以外的通用寫法 */
.ie6fixedTL{position:fixed;left:0;top:0}
.ie6fixedBR{position:fixed;right:0;bottom:0}
/* IE6 專屬 */
* html .ie6fixedTL{position:absolute;left:expression(eval(document.documentElement.scrollLeft));top:expression(eval(document.documentElement.scrollTop))}
* html .ie6fixedBR{position:absolute;left:expression(eval(document.documentElement.scrollLeft+document.documentElement.clientWidth-this.offsetWidth)-(parseInt(this.currentStyle.marginLeft,10)||0)-(parseInt(this.currentStyle.marginRight,10)||0));top:expression(eval(document.documentElement.scrollTop+document.documentElement.clientHeight-this.offsetHeight-(parseInt(this.currentStyle.marginTop,10)||0)-(parseInt(this.currentStyle.marginBottom,10)||0)))}
需要加上邊距時,分別在運算式裡補上數值即可。例如想讓元素距頂與距左各 10px:
/* 通用 */
.ie6fixedTL{position:fixed;left:10px;top:10px}
/* IE6 專屬 */
* html .ie6fixedTL{position:absolute;left:expression(eval(document.documentElement.scrollLeft+10));top:expression(eval(document.documentElement.scrollTop+10))}
這個方法不會影響到其他 absolute 元素,但會出現另一個惱人問題:捲動時元素會「振動」。
IE 採多步驟渲染流程。當你捲動或調整視窗大小時,瀏覽器會重置並重繪整頁,此時才重新計算 CSS 表達式。固定元素必須在重繪後才能跟上捲動位置,中間的時間差就造成了視覺上的跳動。
解法是給 body 或 html 加上 background-attachment:fixed 與一個背景圖,強迫 CSS 在重繪之前先被處理完,表達式自然也會提前運算,跳動就消失了。實測發現這個背景圖不需要是真的圖片,指向 about:blank 即可。
完整程式碼:
/* 通用 */
.ie6fixedTL{position:fixed;left:0;top:0}
.ie6fixedBR{position:fixed;right:0;bottom:0}
/* IE6 專屬 */
/* 修正振動 bug */
* html,* html body{background-image:url(about:blank);background-attachment:fixed}
* html .ie6fixedTL{position:absolute;left:expression(eval(document.documentElement.scrollLeft));top:expression(eval(document.documentElement.scrollTop))}
* html .ie6fixedBR{position:absolute;left:expression(eval(document.documentElement.scrollLeft+document.documentElement.clientWidth-this.offsetWidth)-(parseInt(this.currentStyle.marginLeft,10)||0)-(parseInt(this.currentStyle.marginRight,10)||0));top:expression(eval(document.documentElement.scrollTop+document.documentElement.clientHeight-this.offsetHeight-(parseInt(this.currentStyle.marginTop,10)||0)-(parseInt(this.currentStyle.marginBottom,10)||0)))}
補充提醒:expression 會在每次渲染時被執行,效能開銷不小,若頁面上同時掛多個這類元素,捲動卡頓會相當明顯。這是它除了振動之外另一個不適合大量使用的原因。