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

JavaScript09

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

<body>

<div id="div1" style="width:100px height:100px background:#ccc"></div>

</body>

<script>

var oDiv = document.getElementById('div1')

oDiv.style.position = 'fixed'

oDiv.style.top = '20px'

oDiv.style.left = '20px'

</script>

主要思想就是,在js中修改div的位置。所有的赋值,都可以计算后再传值,这样就不想CSS中只能写一个值了。

新建一个HTML文件,命名为test.html,用于实现把div定位到右上角。

在test.html页面编写一个内容为“这是固定在右上角的DIV”的div,并定义它的id属性为rig,用于下面实现定位。同时,编写几个p标签,用于测试div是否真的固定在页面的右上角。

在test.html页面,使用<style type="text/css"></style>标记定义CSS的内容,在CSS内编写id为rig的div样式。

建议使用css实现,效果更佳,使用position: fixed,固定定位,具体位置的调整是用top、left、right、bottom也可以使用margin调整

css实现代码

<div style="position: fixedtop:100px left: auto right: auto  bottom: auto " ></div>

一般的网站的浮动广告以及浮动菜单等可以使用fixed来实现,js的话需要计算位置以及滚动条滚动时触发事件从而进行计算使用window.onscroll事件代码如下

HTML部分代码

<div style="position:absolutebackground-color:redwidth: 50pxheight: 50px" id="box"></div>

Javascript部分代码

window.onscroll=function(){

    var box= document.getElementById("box")

    var t = document.documentElement.scrollTop || document.body.scrollTop

    box.style.top=t+"px"

}