本文向大家描述一下如何使用Javascript动态创建DIV,首先看一下原来的CSS样式,然后动态创建DIV, 把DIV元素增加到HTML里面,相信本文介绍你会学到很多。
Javascript动态创建DIV
这是原来的CSS样式
.item{float:left;overflow:hidden;margin-left:8px;
margin-top:10px;width:320px;height:250px;
background-repeat:no-repeat;
background-image:url(../images/bgred.jpg)}
.curve{position:relative;width:320px;height:250px;
z-index:1;left:75px;top:-40px;}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
动态创建DIV代码如下:
for(j=0;j*8<str.length;j++)
{
varmyDIV=window.frames["displayFrame"]
.document.createElement("DIV");
myDIV.setAttribute("id","itemDIV"+j);
myDIV.style.styleFloat="left";
myDIV.style.overflow="hidden";
myDIV.style.marginLeft="8px";
myDIV.style.marginTop="10px";
myDIV.style.width="320px";
myDIV.style.height="250px";
myDIV.style.backgroundRepeat="no-repeat";
myDIV.style.backgroundImage="url(image/bgred.jpg)"
window.frames["displayFrame"].document
.body.appendChild(myDIV);
varcurveDIV=window.frames["displayFrame"]
.document.createElement("DIV");
curveDIV.setAttribute("id","curveDIV"+j);
curveDIV.style.position="relative";
curveDIV.style.zIndex=1;
curveDIV.style.left="75px";
curveDIV.style.top="-40px";
curveDIV.style.width="320px";
curveDIV.style.height="250px";
window.frames["displayFrame"].document
.getElementById("DIVitem"+j).appendChild(curveDIV);
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
把DIV元素增加到HTML里面。
也可在HTML里面定义一个SPAN
window.frames["displayFrame"].document
.getElementById("spanId").appendChild(myDIV);
window.frames["displayFrame"].document
.body.appendChild(myDIV);
- 1.
- 2.
- 3.
- 4.
- 5.
IE和Firefox都支持.
◆另外需要注意的是这个CSS元素
浮动效果:float:left
在IE下代码为:myDIV.style.styleFloat="left";
在Firefox代码为:myDIV.style.cssFloat="left";
其他的诸如这种元素:
在CSS编写中一般是:margin-left:8px,而在动态增加需要去掉-:myDIV.style.marginLeft="8px"。
详细出处参考:http://www.jb51.net/article/15938.htm
【编辑推荐】