就像函数名称所暗示的那样,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; }}
如果您确实想在实际工作中使用它,则不要更改style属性,而是定义类并在mouseover,mouseout事件上添加/删除类,以便获得CSS的层叠属性的强大功能。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)