7-2练习
来源:7-2 编程练习
夕落呀
2018-12-31 20:57:58
<!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 btnAdd = document.getElementById('btnAdd');
var btnRemove = document.getElementById('btnRemove');
var list = document.getElementById('list');
var lis = list.getElementsByTagName('li');
for(let i = 0; i < lis.length; i++){
lis[i].onmouseover = function(){
this.style.backgroundColor = 'rgba(0,0,255,.5)';
};
lis[i].onmouseout = function(){
this.style.backgroundColor = 'pink';
};
};
btnAdd.onclick = function(){
var text = lis.length;
var newLi = document.createElement('li');
var newText =document.createTextNode('我是li'+(text+1));
newLi.appendChild(newText);
list.appendChild(newLi);
}
btnRemove.onclick = function(){
list.removeChild(list.children[ (lis.length)-1]);
}
</script>
</body>
</html>
1回答
好帮手慕星星
2019-01-01
同学你好,代码中的问题:
1、点击删除元素,将li元素删除完之后,继续点击,控制台就会报错:
这是因为元素删除完了,继续删除就会出错,所以建议添加一个是否还是元素的判断。
2、将元素删除之后,点击添加元素,前三个元素鼠标移入没有背景颜色的变化,建议将颜色的变化分装起来,点击的时候重新获取li元素,然后调用颜色改变的方法。
自己可以动手试一下,祝学习愉快!
相似问题