js如何在指定位置添加div?

JavaScript011

js如何在指定位置添加div?,第1张

1、利用js代码首先创建一个div,document.createElement('div')

2、确认div添加位置,可以在某个dom元素后面,或者通过css属性控制具体位置,主要通过left/top等属性控制。

3、确定位置之后,显示div即可。

示例:比如html中有一个文本输入框,我们现在需要在挨着输入框右下角位置显示一个div。

<input type="text" id="city" value="beijing"/>

document.createElement()是在对象中创建一个对象,要与appendChild() 或 insertBefore()方法联合使用。

其中,appendChild() 方法在节点的子节点列表末添加新的子节点。insertBefore() 方法在节点的子节点列表任意位置插入新的节点。

1、添加DIV

function addDiv(w,h){

//如果原来有“divCell”这个图层,先删除这个图层

deleteDiv()

//创建一个div

var newdiv = document.createElement("divCell")

//添加到页面

document.body.appendChild(newdiv)

//通过样式指定该div的位置方式,若是想要自己设置div的位置,这句话必须有,把它注释掉你就可以知道效果拉~试试看

newdiv.style.position="absolute"

//通过样式指定x坐标(随机数0~450)

newdiv.style.top= Math.round(Math.random()*450)

//通过样式指定y坐标(随机数0~700)

newdiv.style.left= Math.round(Math.random()*700)

//通过样式指定宽度

newdiv.style.width=w

//通过样式指定高度

newdiv.style.height=h

//通过样式指定背景颜色,,若是背景图片 例为 newdiv.style.backgroundImage="url(img/3.jpg)"

newdiv.style.backgroundColor="#ffffcc"

//添加div的内容

//newdiv.innerHTML=i++

//设置样式透明

newdiv.style.filter = "alpha(opacity=50)"

//设置ID

newdiv.id = "divCell"

}

2、删除DIV

function deleteDiv()

{

var my = document.getElementById("divCell")

if (my != null)

my.parentNode.removeChild(my)

}