实现该效果
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.del{
background-color: cornflowerblue;
font-size: 18px;
float: right;
border: 0;
color: white;
}
#fruit{
width: 100px;
height: 20px;
-webkit-appearance: none;
-moz-appearance: none;
outline: 0;
border-top: 0;
border-right: 0;
border-left: 0;
}
#sure{
background-color: orange;
height: 30px;
width: 80px;
color: white;
border: 0;
}
.f1{
margin-bottom: 10px;
height: 40px;
background-color: cornflowerblue;
width: 150px;
font-size: 20px;
text-align: center;
color: white;
}
</style>
</head>
<body>
<div id="body">
<div class="f1">
<font>香蕉</font>
<button class="del">X</button>
</div>
<div class="f1">
<font>火龙果</font>
<button class="del">X</button>
</div>
<div class="f1">
<font>西瓜</font>
<button class="del">X</button>
</div>
</div>
<div id="">
<input type="text" name="fruit" id="fruit" value="" />
<button id="sure">确定</button>
</div>
</body>
</html>
<script type="text/javascript">
sureNode = document.getElementById("sure")
fruitNode = document.getElementById("fruit")
sureNode.onclick = function(){
console.log(this)
newFruitNode1 = document.createElement("div")
num1 = parseInt(Math.random()*255)
num2 = parseInt(Math.random()*255)
num3 = parseInt(Math.random()*255)
newFruitNode2 = document.createElement("font")
newFruitNode2.innerText = document.getElementById("fruit").value
newFruitNode2.style.backgroundColor = "rgb("+num1+","+num2+","+num3+")"
newFruitNode1.style.backgroundColor = "rgb("+num1+","+num2+","+num3+")"
newFruitNode3 = document.createElement("button")
newFruitNode3.innerText = "X"
newFruitNode3.className = "del"
newFruitNode3.onclick = function(){
console.log(delNodes)
result = confirm("确认删除?")
if(result){
parent = this.parentElement
parent.remove()
}
}
newFruitNode3.style.backgroundColor = "rgb("+num1+","+num2+","+num3+")"
newFruitNode3.style.fontSize = "18px"
newFruitNode3.style.float = "right"
newFruitNode3.style.border = 0
newFruitNode3.style.color = "white"
newFruitNode1.appendChild(newFruitNode2)
newFruitNode1.appendChild(newFruitNode3)
newFruitNode1.className = "f1"
newFruitNode1.style.height = "30px"
newFruitNode1.style.marginTop = 0
bodyNode = document.getElementById("body")
bodyNode.appendChild(newFruitNode1)
}
delNodes = document.getElementsByClassName("del")
for(x=0;x<delNodes.length;x++){
delNode = delNodes[x]
delNode.onclick = function(){
console.log(delNodes)
result = confirm("确认删除?")
if(result){
parent = this.parentElement
parent.remove()
}
}
}
</script>
成品效果: