image.png
1. 制作动态删除和添加内容
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>制作动态删除和添加内容</title>
<style type="text/css">
.div{
position:relative;
background-color: darkseagreen;
text-align: center;
width:200px;
height: 40px;
margin-top: 1px;
}
span{
position: absolute;
height: 40px;
/*line-height: 40px;*/
top: 14px;
left: 80px;
vertical-align: middle;
}
font{
/*text-align: center;*/
position: absolute;
right: 3px;
top: 12px;
}
input{
height: 40px;
border:0;
border-bottom:1px solid rgb(150,150,150)
}
input:focus{
outline:none;
}
button{
background-color: sandybrown;
color: white;
height: 40px;
width: 50px;
}
</style>
</head>
<body>
<div class="div" id="div1">
<span id="">
西瓜
</span>
<font>X</font>
</div>
<div class="div">
<span id="">
火龙果
</span>
<font>X</font>
</div>
<div class="div">
<span id="">
香蕉
</span>
<font>X</font>
</div>
<div class="div">
<span id="">
苹果
</span>
<font>X</font>
</div>
<div>
<input type="text" name="name" id="name" value="" /><label for="name"><button id="add">确定</button></label>
</div>
<script>
fontNodes = document.getElementsByTagName("font")
console.log(fontNodes)
for (x in fontNodes){
fontNodes[x].onclick = function (){
this.parentElement.remove()
}
}
function addItem(value){
addDivNode = document.createElement("div")
addDivNode.style = "class:div;position: relative;float:left;text-align: center;width:200px;height: 40px;"
console.log(addDivNode)
addSpanNode = document.createElement("span")
addSpanNode.innerText = value
addSpanNode.style = "position: absolute;float:left;top: 14px;left: 80px;vertical-align: middle;"
addFontNode = document.getElementsByTagName("font")[0]
addFontNode.innerText = "X"
addFontNode.style = "position: absolute;right: 3px;top: 12px;"
addFontNode.onclick = function (){
this.parentElement.remove()
}
addDivNode.appendChild(addFontNode)
redNum = Math.random()*255+1
greenNum = Math.random()*255+1
blueNum = Math.random()*255+1
addDivNode.appendChild(addSpanNode)
addDivNode.style = "background-color: rgb("+redNum+","+greenNum+","+blueNum+");class:div;position: relative;margin-top: 1px;text-align: center;width:200px;height: 40px;"
bodyNode = document.getElementsByTagName("body")[0]
console.log(bodyNode)
bodyNode.insertBefore(addDivNode,bodyNode.firstElementChild)
console.log(bodyNode)
}
buttonNode = document.getElementById("add")
console.log(buttonNode)
inputNode = document.getElementsByTagName("input")[0]
inputNode.onchange = function(){
value = inputNode.value
console.log(inputNode.value)
buttonNode.onclick = addItem(value)
}
</script>
</body>
</html>