老师,还有什么地方需要修改的吗

来源:7-2 编程练习

为爱修行

2019-03-06 19:38:08

<!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 wrap={
                list:document.getElementById('list'),
                li:document.getElementsByTagName('li'),
                btnAdd:document.getElementById('btnAdd'),
                btnRemove:document.getElementById('btnRemove')
            };

            function changeColor(len){
                for (var i = 0; i < len; i++) {
                    wrap.li[i].onmouseover=function(){
                        this.style.background='purple';
                    }
                    wrap.li[i].onmouseout=function(){
                        this.style.background='pink';
                    }
                }
            }

            wrap.btnAdd.onclick=function(){
                var len=wrap.list.childElementCount;
                var newLi=document.createElement('li');
                var txt=document.createTextNode('我是li'+(len+1));
                newLi.appendChild(txt);
                wrap.list.appendChild(newLi);
                changeColor(wrap.li.length);
            }

            wrap.btnRemove.onclick=function(){
                if(wrap.list.childElementCount>0){
                    wrap.list.removeChild(list.lastElementChild);
                }
            }

            changeColor(wrap.li.length);


    </script>
</body>

</html>


写回答

1回答

好帮手慕星星

2019-03-07

你好,测试的代码,添加和删除元素是没有问题的,鼠标移入元素改变背景颜色应该只有前三个改变,不是全部都改变背景颜色哦。

无论是原本存在的三个元素还是删除之后新添加的元素,都是前三个改变背景颜色。

这个效果可以完善下,祝学习愉快!

0

0 学习 · 4826 问题

查看课程