众所周知IE6不支持CSS属性position:fixed,这个CSS bug与IE6的双倍margin和不支持PNG透明等bug一样臭名昭著。
如何让position:fixed在IE6中工作?
第一种方法:纯CSS解决IE6的position:fixed的bug
html {
_background-image:url(about:blank); /*用浏览器空白页面作为背景*/
_background-attachment:fixed; /* IE6 确保滚动条滚动时,元素不闪动*/
}
#fixedDiv {
width:960px; height:31px; z-index:100; /*设置浮动层次*/
position:fixed; /* IE6以外的浏览器下定位*/
top:50px; /* IE6以外的浏览器下定位*/
_position:absolute; /*IE6 用absolute模拟fixed*/
_top:expression(documentElement.scrollTop+50+"px"); /*IE6 动态设置top位置为50px */
}
fixedDiv为要固定的元素的id。
这里只实现了IE6下CSS position垂直方向的fixed。若要实现水平方向的fixed,设置_left:expression(documentElement.scrollLeft + "px");
第二种方法 用JavaScript解决IE6的position:fixed的bug
<script language="javascript" type="text/javascript">
window.onload = function () {
var n = 100; //top值
var obj = document.getElementById("fixed"); //fixed为固定元素的id,获得position:fixed对象
window.onscroll = function () {
obj.style.top = (document.body.scrollTop || document.documentElement.scrollTop) + n + 'px';
}
window.onresize = function () {
obj.style.top = (document.body.scrollTop || document.documentElement.scrollTop) + n + 'px';
}
}
</script>
这段javascript代码也能解决IE6的position:fixed的bug。