getElementsByClassName在事件发生时更改元素的样式

时间:2013-09-20 22:55:03

标签: javascript css onmouseover getelementsbyclassname

我正在尝试使用

 onmouseover="document.getElementsByClassName().style.background='color'"

将鼠标悬停在另一个页面元素上时,将具有给定类名的所有div的颜色更改为另一种颜色。

这是一个jsfiddle -if任何人都可以提供一些有用的指示,告诉我哪里出错我会很棒,我确信这是一件非常明显的事情,我很想念。它与document.getElementById一起使用,但只改变了第一个div的颜色,而不是所有颜色。

谢谢:)

1 个答案:

答案 0 :(得分:15)

正如函数名称所示,getElementsByClassName不仅返回一个集合,而且只返回一个对象。因此,您需要遍历它们并将颜色应用于它。

document.getElementsByClassName()
                   ^_______

另外你的id部分无效。我不能拥有空格,也不应该再次出现在被违反的网页上:

<th id="colorswitcher A" onmouseover="document.getElementsByClassName('a').style.background='red'">a</th>
<th id="colorswitcher B" onmouseover="document.getElementsByClassName('a').style.background='blue'">b</th>

你可以这样做(你可以查找什么是处理程序并尝试使用它。),不要为处理程序使用内联属性。

window.onload=function(){
    var aColl = document.getElementsByClassName('a'); //Cache the collection here, so that even a new element added with the same class later we can avoid querying this again by using the cached collection.
    var bColl = document.getElementsByClassName('b');

    document.getElementById('A').addEventListener('mouseover', function(){
        changeColor(aColl, 'red');
    });

    document.getElementById('B').addEventListener('mouseover', function(){
        changeColor(bColl, 'blue');
    });
}
function changeColor(coll, color){

    for(var i=0, len=coll.length; i<len; i++)
    {
        coll[i].style["background-color"] = color;
    }
}

<强> Fiddle

如果你真的想要为一些真正的工作做这件事,那么就不要改变样式属性,而是定义类并在mouseover,mouseout事件上添加/删除类,这样你就可以获得css&#39的强大功能。 ;级联财产。