7-2麻烦老师看一下

来源:7-2 编程练习

田马达加斯加

2018-11-12 17:44:06

<!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">

    //此处填写代码


    // 封装添加li的函数

    var addList=function(){

        var lists=document.getElementsByTagName('li');

        var len=lists.length;

        len++;

        var newLi=document.createElement('li');

        var text=document.createTextNode('我是li'+len);

        newLi.appendChild(text);

        list.appendChild(newLi);

        changeStyle();

    }

    // 封装删除li的函数

    var removeList=function(){

        list.removeChild(list.lastElementChild);

    }

    var lists=document.getElementsByTagName('li');

    function changeStyle(){

        for(var i=0;i<3;i++){

            lists[i].onmouseover=function(){

                this.style.backgroundColor='blue';

            }

            lists[i].onmouseout=function(){

                this.style.backgroundColor='pink';

            }

        }

    }

    document.getElementById('btnAdd').onclick=addList;

    document.getElementById('btnRemove').onclick=removeList;

    </script>

</body>


</html>


写回答

1回答

好帮手慕星星

2018-11-12

1、页面打开时,三个li元素鼠标移入没有背景颜色变化,需要提前调用下changeStyle方法。

2、当元素删除小于三个时,点击添加元素按钮,下方会报错,因为for循环中的判断是i<3,也就是当li不够三个时,点击插入元素调用changeStyle方法会报错,但是效果是有的。

所以建议for循环中使用li元素的长度做判断,再加一个i的if条件判断即可,参考:

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

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


0

0 学习 · 4826 问题

查看课程