当前位置:   article > 正文

为table动态添加行;根据行的奇偶性对行的背景色进行设置,以及当鼠标移到该行和离开该行时的背景色_newblock.green-chain.cc

newblock.green-chain.cc

    <script type="text/javascript">
        window.onload = function () {
            var tb1 = document.getElementById("tb1");
            var tr = document.getElementsByTagName("tr");
            document.getElementById("btnAdd").onclick = function () {
                var row = tb1.insertRow();//添加行
                var index = tr.length;//行的索引

                //alert(index);
                var sname = row.insertCell(0);//添加列
                sname.innerText = "a"; //innerText:在添加的列中放入内容。innerHTML:在td中添加控件

                var gender = row.insertCell(1);
                gender.innerText = "男";

                var age = row.insertCell(2);
                age.innerText = "24";
                row.appendChild(sname);//把添加的td放到该行中
                row.appendChild(gender);
                row.appendChild(age);
                //根据索引对行的背景颜色进行设置;以及当鼠标移到该行和离开该行时背景色的变化
                var beforeColor;
                for (var i = 0; i < index; i++) {
                    if (i % 2 == 0) {
                        row.style.backgroundColor = "red";
                    } else {
                        row.style.backgroundColor = "green";
                    }
                    row.onmouseover = function () {
                        beforeColor = this.style.backgroundColor;
                        this.style.backgroundColor = "purple";
                    }
                    row.onmouseout = function () {
                        this.style.backgroundColor = beforeColor;
                    }
                }
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table style="width: 100%;" id="tb1">
            <tr id="1" style="background: red;">
                <td>
                    姓名
                </td>
                <td>
                    性别
                </td>
                <td>
                    年龄
                </td>
            </tr>
        </table>
    </div>
    <input id="btnAdd" type="button" value="button" />
    </form>
</body>
</html>

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/代码探险家/article/detail/969400
推荐阅读
相关标签
  

闽ICP备14008679号