html 通过js给相同class的元素添加事件(鼠标移入与移出)


1. 获得某class的所有对象的方法: (返回的是数组)  这里我是绑定到a链接上

var links = document.querySelectorAll("ul > li > a");  

  或是通过getElementById getElementsByTagName来获取元素

2. for循环给list对象数组的每个对象添加悬停和悬出事件

        for(var i in links)
            {
                links[i].onmouseover = changeColor;
                links[i].onmouseout = delChangeColor;
            }

 3.再定义移出与移入的两个函数

    <script>
        function changeColor() {
            this.style.backgroundColor = '#003366';
            this.style.color = 'white';
        }

        function delChangeColor() {
            this.style.backgroundColor = '#f8f8f8';
            this.style.color = 'black';
        }

    </script>

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM