1.动态添加和删除元素
tool.js
function randomColor(a=1){
red = parseInt(Math.random()*255)
green = parseInt(Math.random()*255)
blue = parseInt(Math.random()*255)
return 'rgba('+red+','+green+','+blue+','+a+')'
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="js/tool.js"></script>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
#box1{
margin-left: 40px;
margin-top: 30px;
}
.fruit{
width: 250px;
height: 60px;
margin: 2px 0;
line-height: 60px;
}
.fruit1{
background-color: rgb(80,141,141);
}
.name1{
float: left;
width: 225px;
height: 100%;
text-align: center;
font-size: 25px;
color: white;
}
.del{
float: right;
font-size: 25px;
width: 25px;
height: 100%;
color: white;
cursor: pointer;
}
#box2 input{
width: 250px;
height: 60px;
border: 0;
margin-left: 40px;
border-bottom: 1px solid rgb(147,147,147);
text-align: center;
font-size: 20px;
}
#box2 input:focus{
outline: 0;
}
#box2 button{
width: 60px;
height: 30px;
vertical-align: bottom;
background-color: rgb(255,105,47);
border: 0;
color: white;
font-size: 20px;
font-weight: bold;
}
</style>
</head>
<body>
<div id="box1">
<div class="fruit1 fruit">
<font class="name1">火龙果</font><font class="del">×</font>
</div>
<div class="fruit1 fruit">
<font class="name1">哈密瓜</font><font class="del">×</font>
</div>
<div class="fruit1 fruit">
<font class="name1">柚子</font><font class="del">×</font>
</div>
<div class="fruit1 fruit">
<font class="name1">芒果</font><font class="del">×</font>
</div>
</div>
<div id="box2">
<input type="" name="" id="fruitName" value="" />
<button onclick="addAction()">确定</button>
</div>
<script type="text/javascript">
//=======添加水果
function addAction(){
//获取输入框中的内容
inputNode = document.getElementById('fruitName')
fruitName = inputNode.value
if(fruitName.length == 0){
alert('请输入水果名')
return
}
//清空输入框
inputNode.value = ''
//创建节点
//创建一个div
var divNode = document.createElement('div')
divNode.style.backgroundColor = randomColor(0.5)
divNode.className = 'fruit'
//创建一个div里面的第一个font
var nameNode = document.createElement('font')
nameNode.className = 'name1'
nameNode.innerText = fruitName
//创建一个div里面的第二个font
var delNode = document.createElement('font')
delNode.className = 'del'
delNode.innerText = '×'
delNode.onclick = delAction
//添加节点
divNode.appendChild(nameNode)
divNode.appendChild(delNode)
box1Node = document.getElementById('box1')
box1Node.insertBefore(divNode, box1Node.firstElementChild)
}
//========删除节点
function delAction(){
console.log(this)
this.parentElement.remove()
}
delNodes = document.getElementsByClassName('del')
for(x=0;x<delNodes.length;x++){
delNode = delNodes[x]
delNode.onclick = delAction
}
</script>
</body>
</html>