
比如
<body>
<div>最上面的div,测试效果,可有可无</div>
<input
type="button"
id="buttonid"
value="插入一个div"
onclick="javascript:document.getelementbyid('buttonid').insertadjacenthtml('beforebegin','<div>new
div</div>')">
</body>
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)
}
<!DOCTYPE html><html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.fadeIn { animation: fadeIn .3s linear forwards background-color: red height: 100px margin-bottom: 10px }
@keyframes fadeIn {
0% { opacity: 0 height: 0 }
100% { opacity: 1 height: 100px }
}
</style>
</head>
<body>
<button id='button'>插入一个div</button>
<div id="content">
</div>
<script>
window.addEventListener('load', function() {
var i = 0
var button = document.getElementById('button')
var conntent = document.getElementById("content")
button.addEventListener('click', function(e) {
var div = document.createElement('div')
div.textContent = i++
div.className = 'fadeIn'
conntent.appendChild(div)
})
})
</script>
</body>
</html>
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)