JS动态添加div

JS动态添加div,第1张

<!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>

添加div,用javascript自带的createElement创建一个div就可以了;

<script>

    var oDiv = document.createElement('div')

    oDiv.innerHTML = '添加的div'

    document.body.appendChild(oDiv)

</sciprt>

这样就可以了。

2个方式。

1。修改innerHTML。例如:

document.getElementByID(...).onclick=function(){

document.getElementByID(...).innerHTML="<div class='newdiv'>我是新的div</div>"//获取要增加div的父节点

}

2.增加节点、

document.getElementByID(...).onclick=function(){

var newDiv=document.createElemen("div")//创建一个新的div节点

document.getElementByID(..).appendChild(newDiv)

}

有问题请追问


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

原文地址: http://outofmemory.cn/bake/11864172.html

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

发表评论

登录后才能评论

评论列表(0条)

保存