老师这样对吗?

来源:7-2 编程练习

白衣未央_Toy

2019-02-12 14:32:44

 <!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;
        padding-bottom: 50px;
    }
    /*ul默认有外边距*/

    ul {
        width: 300px;
        height: 100%;
        background-color: #f9c3e6d6;
        list-style: none;
        /*清除默认边距*/
        margin: 0;
        padding: 0;
        margin: 20px auto;
        margin-bottom: 30px;
        padding-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>
    	(function () {
		    var btnAdd = document.getElementById("btnAdd");
    		var btnRemove = document.getElementById("btnRemove");
    		var list = document.getElementById("list");
    		var li = document.getElementsByTagName("li")
    		var createLi = null;
    		var txt = null;
    		btnAdd.onclick = function () {
    			var createLi = document.createElement("li");
    			var txt = document.createTextNode("我是li"+(li.length+1));
    			createLi.appendChild(txt);
    			list.appendChild(createLi);
    		}
    		btnRemove.onclick = function () {
    			var len = list.childElementCount;
    			if (len == 0) return;
    			list.removeChild(list.children[len-1])
    		}
    			for (var i = 0; i  < 3; i++) {
	    			li[i].onmouseover = function () {
	    				this.style.background = 'purple'
	    			}
	    			li[i].onmouseout = function () {
	    				this.style.background = 'pink'
	    			}
    			}
    	})()
    </script>
</body>

</html>


写回答

1回答

好帮手慕星星

2019-02-12

你好,添加元素和删除元素效果是正确的,但是当删除完前三个元素或者任意一个之后,点击添加元素,新添加的元素(在前三个之内),鼠标移入没有改变背景颜色。

可以将背景颜色改变的代码封装起来,点击添加元素的时候调用即可,自己可以试一下。

祝学习愉快!

0

0 学习 · 4826 问题

查看课程