7 javascript css onmouseover getelementsbyclassname
我正在尝试使用
onmouseover="document.getElementsByClassName().style.background='color'"
Run Code Online (Sandbox Code Playgroud)
将鼠标悬停在另一个页面元素上时,将具有给定类名的所有div的颜色更改为另一种颜色.
这是一个jsfiddle - 如果有人可以提供一些有用的指示,我会在哪里出错,那将是很好的,我确信这是一个非常明显的我缺少的东西.它与document.getElementById一起使用,但只改变了第一个div的颜色,而不是所有颜色.
谢谢 :)
PSL*_*PSL 18
正如函数名称所示,getElementsByClassName不仅返回一个集合,而且只返回一个对象.因此,您需要循环遍历它们并将颜色应用于它.
document.getElementsByClassName()
^_______
Run Code Online (Sandbox Code Playgroud)
另外你的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>
Run Code Online (Sandbox Code Playgroud)
你可以这样做(你可以查找什么是处理程序并尝试使用它.),不要为处理程序使用内联属性.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
如果你真的想要为一些实际的工作做,那么不要改变样式属性,而是定义类并在mouseover,mouseout事件上添加/删除类,这样你就可以获得css'cascading属性的强大功能.
| 归档时间: |
|
| 查看次数: |
54595 次 |
| 最近记录: |