首页 > 技术文章 > html 通过js给相同class的元素添加事件(鼠标移入与移出)

ramsey 2020-11-30 10:07 原文

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>

  

推荐阅读