zoukankan      html  css  js  c++  java
  • day16--Dom鼠标操作

    1、有一个表格,当鼠标移动到某行时,该行变红,移除时,变为白色

    <body> 
            <table border="1" width="300px">
                <tr onmouseover="t1(0);" onmouseout="t2(0);">
                    <td>1</td>
                    <td>2</td>
                    <td>3</td>
                </tr>
                <tr onmouseover="t1(1);" onmouseout="t2(1);">
                    <td>1</td>
                    <td>2</td>
                    <td>3</td>
                </tr>
                <tr onmouseover="t1(2);" onmouseout="t2(2);">
                    <td>1</td>
                    <td>2</td>
                    <td>3</td>
                </tr>
            </table>
            <script>
                function t1(n){
                    var myTrs=document.getElementsByTagName("tr")[n];
                    //console.log(myTrs);
                    myTrs.style.backgroundColor="red";
                }
                function t2(n){
                    var myTrs=document.getElementsByTagName("tr")[n];
                    myTrs.style.backgroundColor="white";
                }
            </script>
        </body>

     该示例当鼠标移动到某一行时,改行变为红色,移开改行变为白色;

    以上代码需要将每行都进行绑定,即需要将每个tr标签进行绑定,如果tr标签太多的话,该方法可能不适用;我们可以通过以下方式来实现:

              <table border="1" width="300px">
                <tr>
                    <td>1</td>
                    <td>2</td>
                    <td>3</td>
                </tr>
                <tr>
                    <td>1</td>
                    <td>2</td>
                    <td>3</td>
                </tr>
                <tr>
                    <td>1</td>
                    <td>2</td>
                    <td>3</td>
                </tr>
            </table>
            <script>
                var myTrs=document.getElementsByTagName("tr");
                var len=myTrs.length;
                for(var i=0;i<len;i++){
                    myTrs[i].onmouseover=function(){
                        this.style.backgroundColor="red";
                        // myTrs[i].style.backgroundColor="red";这种写法不可以
                        //谁调用该函数,this就指向谁
                    }
                    myTrs[i].onmouseout=function(){
                        this.style.backgroundColor="";
                        //谁调用该函数,this就指向谁
                    }
                }            
            </script>

    这种方式简化了一点代码;执行结果是一样的

  • 相关阅读:
    面向对象的六大原则
    系统整体框架介绍
    键盘控制div上下左右移动 (转)
    逆向wireshark学习SSL协议算法(转)
    在CentOS下安装配置MySQL(转)
    ps 专题
    用Linux/Unix命令把十六进制转换成十进制(转)
    2014由于在myeclipse5.5.1许可证
    美国地名索引(在美国的英文名市、中国)
    Memcache存储大量数据的问题
  • 原文地址:https://www.cnblogs.com/wuxiaoru/p/12593936.html
Copyright © 2011-2022 走看看