<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="too.js">
</script>
<style type="text/css">
.fruitBox{
width: 250px;
height: 60px;
background-color: green;
/*创建间距*/
margin-bottom: 5px;
/*垂直居中*/
line-height: 60px;
/*水平居中*/
/*text-align: center;*/
}
.fruitName{
float: left;
width: 230px;
text-align: center;
font-size: 20px;
color: white;
}
.close{
font-size: 20px;
color: white;
/*设置光标样式*/
cursor: pointer;
}
/*输入框*/
#newFruit{
/*清除所有边框*/
border: 0;
border-bottom: 1px solid black;
font-size: 30px;
width: 250px;
/*光标居中*/
text-align: center;
/*设置输入框和确定按钮一样*/
vertical-align: bottom;
}
/*清除边框颜色*/
#newFruit:focus{
outline: 0;
}
/*确定按钮*/
#sure{
/*清除边框*/
border: 0;
background-color: goldenrod;
color: white;
font-size: 20px;
width: 70px;
height: 40px;
}
#sure:focus{
/*清除边框颜色*/
outline: 0;
}
</style>
</head>
<body>
<div id="show"></div>
<div id="add">
<input type="" name="newFruit" id="newFruit" value="" />
<button id="sure" onclick="addNewFruit()">确定</button>
</div>
<!--默认显示的水果-->
<script type="text/javascript">
function creatFruitNode(name){
//创建水果节点
var divNode = document.createElement('div')
divNode.className = 'fruitBox'
//水果名字节点
var nameNode = document.createElement('font')
nameNode.innerText = name
nameNode.className = 'fruitName'
//关闭按钮
var closeNode = document.createElement('font')
closeNode.innerText = 'x'
closeNode.className = 'close'
//关闭按钮添加点击事件
closeNode.addEventListener('click',function(){
//移除被点击的节点的父节点
this.parentElement.remove()
})
divNode.appendChild(nameNode)
divNode.appendChild(closeNode)
return divNode
}
fruitArray = ['苹果','香蕉','梨','西瓜']
//展示所有的节点
showNode = document.getElementById('show')
for(index=0;index<fruitArray.length;index++){
//拿水果名
fruitName = fruitArray[index]
//创建对应的节点
fruitNode = creatFruitNode(fruitName)
//添加水果节点
showNode.appendChild(fruitNode)
}
//点击确认按钮
function addNewFruit(){
//拿到输入水果名
var newFruitName = document.getElementById('newFruit').value
//创建对应的节点
var newFruitNode = creatFruitNode(newFruitName)
newFruitNode.style.backgroundColor=randomColor()
//添加节点
showNode.insertBefore(newFruitNode,showNode.firstElementChild)
//清空输入框
document.getElementById('newFruit').value=''
}
</script>
</body>
</html>
js代码
//随机颜色
function randomColor(){
var r = parseInt(Math.random()*255)
var g = parseInt(Math.random()*255)
var b = parseInt(Math.random()*255)
//实现拼接rgb(44,4,5)
return 'rgb('+r+','+g+','+b+')'
}

image.png
网友评论