麻烦老师检查

来源:11-2 编程练习

leiyihai

2019-11-11 13:57:37

<!DOCTYPE html>
<html>

<head>
    <title>DOM操作练习</title>
    <style type="text/css">
    html,
    body {
        margin: 0;
        padding: 0;
    }

    div:not(:nth-of-type(2)) {
        width: 500px;
        height: 100%;
        background-color: #a0e4ff;
        margin: 0 auto;
    }
    /*ul默认有外边距*/

    ul {
        width: 300px;
        height: 100%;
        background-color: #ecc7ea;
        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">
    //获取ul、li、添加按钮、删除按钮
    var list=document.getElementById("list");
    var li=document.getElementsByTagName("li");
    var btnAdd=document.getElementById("btnAdd");
    var btnRemove=document.getElementById("btnRemove");
    //li绑定移入事件
    for (var i=0,len=li.length;i<len;i++){
        li[i].onmouseover=function(){
            this.style.backgroundColor="purple"; 
        }
    }
    //li绑定移出事件
    for (var i=0,len=li.length;i<len;i++){
        li[i].onmouseout=function(){
            this.style.backgroundColor="#eb8787"; 
        }
    }
    //添加按钮绑定事件
    btnAdd.onclick=function(){
        var liLen=li.length;
        text=document.createTextNode("我是li"+(liLen+1));
        newLi=document.createElement("li");
        newLi.appendChild(text);
        list.appendChild(newLi);
    }
    //删除按钮绑定事件
    btnRemove.onclick=function(){
        if (list.children.length==0){
            return;
        }
        var lastChild=list.lastElementChild;
        list.removeChild(lastChild);
    }
    
    </script>
</body>

</html>

老师,我想尝试实现不管删除还是增加所有的li都具有移入和移出事件,老师能给个思路吗?

写回答

1回答

好帮手慕粉

2019-11-11

同学你好,首先代码实现的是正确的。同学可以将鼠标移入移出li修改颜色的方法写一个函数,在点击添加的方法中调用哦,自己可以尝试着实现一下。

如果我的回答帮助到了你,欢迎采纳,祝学习愉快~

0

0 学习 · 40143 问题

查看课程