找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 1862|回复: 0

[教程] css固定元素位置(fixed)

[复制链接]
发表于 2013-4-7 15:56:28 | 显示全部楼层 |阅读模式 来自 北京市
我们经常碰到的需求是希望页面某个元素固定在浏览器的一个位置,无论如何滚动滚动条,位置不变,就例如经常看到的弹出广告。方法一般是使用js控制,或者使用css。这里我写的是css的控制方法。
在IE7以上版本及firefox、opera、safari里,都支持css属性"position:fixed",它的作用就是将元素相对于窗口固定位置。代码如下

1
#ads{

[backcolor=rgb(248, 248, 248) !important]
2
    position:fixed;

3
    right:0;

[backcolor=rgb(248, 248, 248) !important]
4
    bottom:0;

5
    border:1px solid red;

[backcolor=rgb(248, 248, 248) !important]
6
    width:300px;

7
    height:250px;

[backcolor=rgb(248, 248, 248) !important]
8
}



我们定义一个#ads的id样式,并给他设了高度宽度,通过position:fixed以及right、bottom将元素定位在窗口右下角。
但是在IE6下,并不支持position:fixed属性,这个时候我们需要对IE6进行hack处理。解决的方案是使用postion:absolute属性,它的作用大家都很熟悉,相对于父元素进行绝对定位,然后我们可以通过expression来改变#ads的top值。
PS expression的定义:IE5及其以后版本支持在CSS中使用expression,用来把CSS属性和Javas cript表达式关联起来,这里的CSS属性可以是元素固有的属性,也可以是自定义属性。就是说CSS属性后面可以是一段Javas cript表达式,CSS属性的值等于Javas cript表达式计算的结果。 在表达式中可以直接引用元素自身的属性和方法,也可以使用其他浏览器对象。这个表达式就好像是在这个元素的一个成员函数中一样。
所以我们可以通过在css里计算javascript值来改变top值,代码如下:
1
#ads{

[backcolor=rgb(248, 248, 248) !important]
2
    _position:absolute;

3
    _top:expression(documentElement.scrollTop + documentElement.clientHeight-this.offsetHeight);

[backcolor=rgb(248, 248, 248) !important]
4
}



似乎一切都完美了,但是我们在IE6下运行的时候会发现,随着滚动条的移动,我们的这个#ads朋友他会抖动。解决方法也很简单,只要在body里加一点点的css,如下:

1
body{

[backcolor=rgb(248, 248, 248) !important]
2
    background-image:url(about:blank); /* for IE6 */

3
    background-attachment:fixed; /*必须*/

[backcolor=rgb(248, 248, 248) !important]
4
}



好啦,完工!!!!!!!!!!!!!!!!!!!!!!!!
有木有!!!!!!!!!!!!!!!!!!!!!!!!
PS:原本使用的是"url(text.txt)",但是txt这个是不存在的,http请求报404错误,导致影响加载速度,参考了网上的一些写法,使用about:blank可以达到相同目的。
原理据说是ie6不支持fixed 而其样式背景却支持fixed,通过背景来此消彼长消除抖动,望大牛指教。
完整的代码:
01
body{

[backcolor=rgb(248, 248, 248) !important]
02
    background-image:url(about:blank); /* for IE6 */

03
    background-attachment:fixed; /*必须*/

[backcolor=rgb(248, 248, 248) !important]
04
}

05
#ads{

[backcolor=rgb(248, 248, 248) !important]
06
    width:300px;

07
    height:250px;

[backcolor=rgb(248, 248, 248) !important]
08
    position:fixed;

09
    right:0;

[backcolor=rgb(248, 248, 248) !important]
10
    bottom:0;

11
    _position:absolute;

[backcolor=rgb(248, 248, 248) !important]
12
    _top:expression(documentElement.scrollTop + documentElement.clientHeight-this.offsetHeight);

13
    border:1px solid red;

[backcolor=rgb(248, 248, 248) !important]
14
}




发帖求助前要善用【论坛搜索】功能,那里可能会有你要找的答案;

如何回报帮助你解决问题的坛友,好办法就是点击帖子下方的评分按钮给对方加【金币】不会扣除自己的积分,做一个热心并受欢迎的人!

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则 需要先绑定手机号

关闭

站长推荐上一条 /1 下一条

QQ|侵权投诉|广告报价|手机版|小黑屋|西部数码代理|飘仙建站论坛 ( 豫ICP备2022021143号-1 )

GMT+8, 2024-5-19 02:40 , Processed in 0.046376 second(s), 9 queries , Redis On.

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表