div的样式中使用相当于浏览器窗口定位——position:fixed
一、position:fixed;属性的含义
fixed:生成绝对定位的元素,相对于浏览器窗口进行定位。元素的位置通过 “left”, “top”, “right” 以及 “bottom” 属性进行规定。
我们平时所说的固定定位指的就是 fixed,设置了固定定位的元素不会随滚动条上下滚动。
二、一般的 position:fixed; 实现方法
#top{position:fixed;bottom:0;right:20px}
实现了 id 为 top 的元素固定在浏览器的底部和距离右边 20 个像素的位置
#top{position:fixed;top:20px;right:20px}
实现了 id 为 top 的元素固定在距离浏览器的顶部 20 个像素和距离右边 20 个像素的位置
三、ie6下position:fixed; 实现方法
在ie6中是不能直接使用 position:fixed; 你需要一些 css hack 来解决它
相同的还是让元素固定在浏览器的底部和距离右边的 20 个像素,这次的代码是:
#top{
position:fixed;
bottom:0;
right:20px;
_position:absolute;
_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 才能识别,目的是为了区分其他浏览器。
1.使元素固定在浏览器窗口的顶部:
#top{
_position:absolute;
_top:expression(eval(document.documentelement.scrolltop));
}
2.使元素固定距浏览器窗口的顶部 a 像素的位置:
#top{
_position:absolute;
_top:expression(eval(document.documentelement.scrolltop));
_margin-top:a;
}
或者
#top{
_position:absolute;
_top:expression(eval(document.documentelement.scrolltop+a));
}
3、使元素固定在浏览器窗口的底部:
#top{
_position:absolute;
_top:expression(eval(document.documentelement.scrolltop+document.documentelement.clientheight-this.offsetheight-(parseint(this.currentstyle.margintop,10)||0)-(parseint(this.currentstyle.marginbottom,10)||0)));
}
4、使元素固定在距浏览器窗口的底部 b 像素的位置:
#top{
_position:absolute;
_top:expression(eval(document.documentelement.scrolltop+document.documentelement.clientheight-this.offsetheight-(parseint(this.currentstyle.margintop,10)||0)-(parseint(this.currentstyle.marginbottom,10)||0)));
_margin-bottom:b;
}
或者
#top{
_position:absolute;
_top:expression(eval(document.documentelement.scrolltop+document.documentelement.clientheight-this.offsetheight-(parseint(this.currentstyle.margintop,10)||b)-(parseint(this.currentstyle.marginbottom,10)||b)));
}
四、ie6下的闪动问题
问题还没有完全解决。在用了上面的办法后,你会发现:被固定定位的元素在滚动滚动条的时候会闪动。解决闪动问题的办法是在 css 文件中加入:
*html{background-image:url(about:blank);background-attachment:fixed;}
其中 * html选择器 hack 是给 ie6 识别的
到此,ie6 的 position:fixed; 问题就已完全解决了。