关于fixed问题
在网页中经常会遇到,某一元素在滚动一定距离后会出现,并一直定位在某一位置。
如导航在顶部固定。
css 中 position:fixed; 即可实现,定位问题。
但是滚动怎么做那?
1 function getScrollTop() { 2 var scrollPos; 3 if (window.pageYOffset) { 4 scrollPos = window.pageYOffset; } 5 else if (document.compatMode && document.compatMode != 'BackCompat') 6 { scrollPos = document.documentElement.scrollTop; } 7 else if (document.body) { scrollPos = document.body.scrollTop; } 8 return scrollPos; 9 }
getScrollTop能得到滚动距离(支持ie6)
1 window.onscroll = function() { 2 var yheight = getScrollTop(), 3 height = document.documentElement.clientHeight, 4 //后面数值自己改 5 top = parseInt(yheight) + parseInt(height) - 1078, 6 //要定位元素 7 nav = document.getElementById('webNav'); 8 var L1 = nav.offsetWidth; 9 var Left = (document.documentElement.clientWidth - L1) / 2; 10 if (top > 0) { 11 nav.style.position = "fixed"; 12 nav.style.top = 0; 13 nav.style.left = Left + 'px'; 14 } else { 15 nav.style.position = "relative"; 16 nav.style.left = 0; 17 } 18 }
就像你所遇到的问题一样, IE6 有太多的 bug 让制作网页的人头疼。
如何解决 IE6 不支持 position:fixed; 属性的办法。
在 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 固定定位问题的。

浙公网安备 33010602011771号