我不明白为什么我不能在我的代码中操纵.special的样式。我确信这很简单,但它不起作用。
<h1>I am an h1!</h1>
<p id="first" class="special">Hello</p>
<p class="special">Goodbye</p>
<p>Hi Again</p>
<p id="last">Goodbye Again</p>
var x = document.getElementsByClassName("special");
x.style.color = "blue";
答案 0 :(得分:2)
getElementsByClassName不只返回一个集合。因此,您需要遍历它们并将颜色应用于它。以下是鼠标事件的示例。
window.onload=function(){
var hiClass = document.getElementsByClassName("special");
document.getElementById('A').addEventListener('mouseover', function(){
changeColor(hiClass, 'red');
});
document.getElementById('A').addEventListener('mouseout', function(){
changeColor(hiClass, 'blue');
});
document.getElementById('B').addEventListener('mouseover', function(){
changeColor(hiClass, 'blue');
});
document.getElementById('B').addEventListener('mouseout', function(){
changeColor(hiClass, 'red');
});
}
function changeColor(coll, color){
for(var i=0, len=coll.length; i<len; i++)
{
coll[i].style["background-color"] = color;
}
}
&#13;
.a {
width:50px;
height:50px;
background-color:blue;
margin-top:15px;
}
.b {
width:50px;
height:50px;
background-color:red;
margin-top:10px;
}
th {
padding:20px;
width:30px;
height:30px;
background-color:green;
}
&#13;
<table>
<tr>
<th id="A" >a</th>
<th id="B" >b</th>
</tr>
</table>
<h1>I am an h1!</h1>
<p id="first" class="special">Hello</p>
<p class="special">Goodbye</p>
<p>Hi Again</p>
<p id="last">Goodbye Again</p>
&#13;
答案 1 :(得分:1)
使用for of
语句迭代您收到的集合。
for (const s of document.getElementsByClassName("special")) {
s.style.color = "blue";
}
我会亲自使用querySelectorAll
,因为它更通用,并且可以轻松地按类获取。
for (const s of document.querySelectorAll(".special")) {
s.style.color = "blue";
}
最后,如果所有.special
类都应该使用该样式,那么您可能只需将其添加到CSS中即可。
.special {
color: blue;
}
这取决于您可能未包含在问题中的其他逻辑。即便如此,你也许可以通过添加另一个类来逃避,甚至可能是一些祖先元素。
答案 2 :(得分:0)
getElementsByClassName
返回所有元素的列表,其中包含类&#34; special&#34;,而不只是一个(因为可能有多个具有相同类名的元素)。
如果你想获得带有#34; special&#34;的第一个元素,请改为:
var x = document.getElementsByClassName("special");
x[0].style.color = "blue";
要使用class&#34; special&#34;更改所有元素的样式,您可以使用经典for循环:
var x = document.getElementsByClassName("special");
for (var i=0; i<x.length; i++) {
x[i].style.color = "blue";
}
答案 3 :(得分:0)
因为x
作为对象数组返回。您可以使用jQuery返回更多可操作对象的列表,或者对返回进行计数,并遍历数组,随时设置每个项目的属性。
答案 4 :(得分:0)
document.getElementsByClassName返回一个类似数组的对象。你需要这样引用它。
var x = document.getElementsByClassName("special")[0]; //Get the first element with the class name
x.style.color = "blue";