【问题标题】:getElementsByClassName to change the style of elements when event occurs [duplicate]getElementsByClassName 在事件发生时更改元素的样式[重复]
【发布时间】:2013-09-26 10:43:55
【问题描述】:

我正在尝试使用

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

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

这是一个 jsfiddle - 如果有人可以就我哪里出错提供一些有用的指示,那就太好了,我敢肯定我错过了一些非常明显的东西。它与 document.getElementById 一起工作,但这只改变了第一个 div 的颜色,而不是全部。

谢谢:)

【问题讨论】:

标签: javascript css onmouseover getelementsbyclassname


【解决方案1】:

正如函数名所暗示的,getElementsByClassName 返回一个集合,而不仅仅是一个对象。所以你需要遍历它们并为其应用颜色。

document.getElementsByClassName()
                   ^_______

另外,您的 id 部分无效。 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 级联属性的强大功能。

【讨论】:

  • 您好,感谢您的回答!我有点菜鸟,我将如何遍历它们? *编辑:固定 ID。谢谢。
  • 可能很重要的一点是,getElementsByClassName 返回一个实时集合,这就是为什么您可以在函数顶部“缓存”aCollbColl(否则,您将拥有在事件处理程序中重新查询)。无论哪种方式,答案都很好。
  • @lan 是的。很好的补充。
猜你喜欢
  • 2018-11-20
  • 1970-01-01
  • 2015-10-07
  • 1970-01-01
  • 2018-08-12
  • 1970-01-01
  • 2021-12-23
  • 2011-11-28
相关资源
最近更新 更多