还可以更简洁,更优化么?

来源:7-2 编程练习

陈子长

2018-12-25 17:45:00

<!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.querySelectorAll('li');
    var btnAdd = document.getElementById('btnAdd');
    var btnRemove = document.getElementById('btnRemove');
    var list = document.getElementById('list');
    var count = 3;

    for (var i = 0 ; i < li.length ; i++) {
        li[i].onmouseover = function(){
            this.style.backgroundColor = '#ccc';
        }
        li[i].onmouseout = function(){
            this.style.backgroundColor = '#cdffc0';
        }
    }

    btnAdd.onclick = function() {
        count++;
        var newLi = document.createElement('li');
        var txt = document.createTextNode('我是li' + count);

        newLi.appendChild(txt);
        list.appendChild(newLi);
    }

    btnRemove.onclick = function () {
        list.removeChild(list.lastElementChild);
        count--;
        if(count <= 0 ) {
            count = 0;
        }
    }
</script>
</body>

</html>


写回答

1回答

好帮手慕星星

2018-12-25

同学你好,点击和删除元素的效果是可以的,但是将原有的元素删除再添加之后,鼠标移入前三个是没有背景颜色的效果变化的,建议将颜色变化的样式封装起来,里面重新获取li元素,判断li元素的长度,参考:

http://img.mukewang.com/climg/5c2208cb0001d61b08660530.jpg

http://img.mukewang.com/climg/5c2208f7000193da10020344.jpg

自己完善测试下,祝学习愉快!

1

0 学习 · 4826 问题

查看课程