符合要求吗?
来源:7-2 编程练习
非凡哥大战哥斯拉
2019-01-21 13:26:39
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
html,
body {
margin: 0;
padding: 0;
}
div:not(:nth-of-type(2)) {
width: 500px;
height: 100%;
background-color: #00c4ff7a;
margin: 0 auto;
}
/*ul默认有外边距*/
ul {
width: 300px;
height: 100%;
background-color: #f9c3e6d6;
list-style: none;
/*清除默认边距*/
margin: 0;
padding: 0;
margin: 20px auto;
margin-bottom: 30px;
}
li {
width: 200px;
height: 30px;
line-height: 30px;
margin: 30px auto;
background-color: #cdffc0;
}
</style>
</head>
<body>
<div id="box">
<button id="btnAdd">添加元素</button>
<button id="btnRemove">删除元素</button>
<ul id="list">我是ul
<li>我是li1</li>
<li>我是li2</li>
<li>我是li3</li>
</ul>
</div>
<script type="text/javascript">
var li = document.getElementsByTagName("li");
var ul = document.getElementById("list");
var addBtn = document.getElementById("btnAdd");
var reBtn = document.getElementById("btnRemove");
var operate = {
change:function(dom){
dom.style.backgroundColor = "lightblue";
},
reback:function(dom){
dom.style.backgroundColor = "pink";
},
addItem:function(){
var len = (li.length) + 1;
var newLi = document.createElement("li");
newLi.innerHTML = "我是li"+len;
ul.appendChild(newLi)
},
removeItem:function(){
ul.removeChild(ul.lastChild)
}
}
for(var i = 0; i < li.length;i++){
li[i].onmouseover = function(){
operate.change(this)
};
li[i].onmouseout = function(){
operate.reback(this)
}
}
addBtn.onclick = function(){
operate.addItem()
}
reBtn.onclick = function(){
operate.removeItem()
}
</script>
</body>
</html>
1回答
你好,代码中的问题:
1、一开始就点击‘删除元素’,需要点击两次才能删除一个li,是因为原有ul中是包含文本节点的:
点击第一次删除的是text,点击第二次删除的才是li元素,所以会产生点击两次才能删除的问题。而点击‘添加元素’按钮直接添加的是li元素,没有text,所以不会有问题。可以修改为:
使用lastElementChild属性直接删除li元素即可,当删除到没有元素的时候返回,否则会报错。
2、当把元素删除点击添加元素之后,前面三个元素鼠标移入没有改变背景颜色,需要完善一下。
祝学习愉快!
相似问题