如何用JS让DIV固定在一个位置

如何用JS让DIV固定在一个位置,第1张

<body>
<div id="div1" style="width:100px; height:100px; background:#ccc";></div>
</body>
<script>
var oDiv = documentgetElementById('div1');
oDivstyleposition = 'fixed';
oDivstyletop = '20px';
oDivstyleleft = '20px';
</script>
主要思想就是,在js中修改div的位置。所有的赋值,都可以计算后再传值,这样就不想CSS中只能写一个值了。

设置div为固定位置。如:
1

<div style="width:100px; height:100px; border:1px solid red; position:fixed; left:300px; top:300px;"></div>
这样就会固定在left:300px;top:300px;的位置,不会随着滚动条的滚动而滚动

这个跟jsp没有关系的你可以在css里控制
#glideDiv0{position:fixed; bottom:0;left:0; width:100%; background:#F00;}
在这里加上
使元素固定在浏览器的顶部:
#glideDiv0{_position:absolute;_bottom:auto;_top:expression(eval(documentdocumentElementscrollTop));}
使元素固定在浏览器的底部:
#glideDiv0{_position:absolute;_bottom:auto;_top:expression(eval(documentdocumentElementscrollTop+documentdocumentElementclientHeight-thisoffsetHeight-(parseInt(thiscurrentStylemarginTop,10)||0)-(parseInt(thiscurrentStylemarginBottom,10)||0)));}
这两段代码只能实现在最底部跟最顶部,你可以使用 _margin-top:10px; 或者 _margin-bottom:10px; 修改其中的数值控制元素的位置。
position:fixed; 闪动问题
现在,问题还没有完全解决。在用了上面的办法后,你会发现:被固定定位的元素在滚动滚动条的时候会闪动。解决闪动问题的办法是在 CSS 文件中加入:
html{background-image:url(about:blank);background-attachment:fixed;}
其中 是给 IE6 识别的。

CSS中的position property一共有四种:

postion: static

postion: relative

position: fixed

position: absolute

如果设置div为static postion, div的位置将不受top,right,left,button等变量的影响,而是按照正常的页面布局进行排版。例:

divstatic {
        position: static;
        border: 3px solid #8AC007;
    }

如果设置div为relative position, 其变量的值将会使div的位置相对其正常(default)位置进行移动。例:

divrelative {
        position: relative;
        left: 30px;
        border: 3px solid #8AC007;
    }

如果设置div为fixed position, div将会被固定在窗口的固定位置。也就是说无论你如何上下移动页面, div在屏幕上显示的位置始终不变。

divfixed {
        position: fixed;
        bottom: 0;
        right: 0;
        width: 300px;
        border: 3px solid #8AC007;
    }

如果设置div为absolute position, div将会相对于其最近的position ancestor定位。absolute position是可以随页面移动而移动在屏幕上的位置的。

divabsolute {
        position: absolute;
        top: 80px;
        right: 0;
        width: 200px;
        height: 100px;
        border: 3px solid #8AC007;
    }

以上CSS你可以放到自己的网页应用里试一下,区别就很明显了。

参考资料:

>使用绝对定位可以事项这个功能,即position: position:absolute; 然后在设置DIV相对与父容器的位置,例如下面这个例子实现将DIV定位在浏览器的左上角 <style type="text/css"> #top { width:400px; height:400px; background-color:#ff0000; position:absolute; left:0px; top:0px; } </style> <body> <div id="top" > </div> </body>

使用绝对定位可以事项这个功能,即position: position:absolute; 然后在设置DIV相对与父容器的位置,例如下面这个例子实现将DIV定位在浏览器的左上角 <style type="text/css"> #top { width:400px; height:400px; background-color:#ff0000; position:absolute; left:0px; top:0px; } </style> <body> <div id="top" > </div> </body>


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/yw/10416844.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-08
下一篇2023-05-08

发表评论

登录后才能评论

评论列表(0条)

    保存