老师帮我看看

来源:7-2 编程练习

慕设计0337955

2018-10-11 21:38:01

<!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">
    //此处填写代码
    //改变背景颜色
    (function(){
        var list=document.getElementById('list');
        var li=list.getElementsByTagName('li');
        console.log(li);
        for(var i=0;i<3;i++){
            li[i].onmouseover=function(){
                this.style.backgroundColor='purple';
          }
            li[i].onmouseout=function(){
               this.style.backgroundColor='pink';
          }
      }
      //添加元素
      var j=4;
     document.getElementById('btnAdd').onclick=function(){   
        var newli=document.createElement('li'),
            txt=document.createTextNode('我是li'+j);
        newli.appendChild(txt);
        list.appendChild(newli);
        j++;
    }
    //删除元素
    document.getElementById('btnRemove').onclick=function(){
        list.removeChild(list.lastElementChild);
    }
    
    })()
    

   
    </script>
</body>

</html>

写回答

1回答

好帮手慕星星

2018-10-12

代码中的问题:

1、添加内容之后删除,继续添加,那么数字就会不对:

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

2、当删除的数量小于三个的时候,再添加,那么前三个中心添加的内容鼠标移入上去是没有背景颜色的变化的。

建议每次添加内容或者是改变元素背景颜色的判断,都要重新获取一下,元素的长长度,这样才不会弄错,参考:

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

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

0

0 学习 · 4826 问题

查看课程