我不明白为什么我不能在我的代码中操作.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";发布于 2017-08-16 03:21:19
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;
}
}.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;
}<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>
发布于 2017-08-16 03:11:21
使用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;
}这将取决于您可能没有包含在问题中的其他逻辑。即使这样,您也可以添加另一个类,甚至可以添加到某个祖先元素中。
发布于 2017-08-16 03:10:15
getElementsByClassName返回类为"special“的所有元素的列表,而不仅仅是一个(因为可以有多个元素具有相同的类名)。如果你想得到第一个带有"special“类的元素,可以这样做:
var x = document.getElementsByClassName("special");
x[0].style.color = "blue";要更改类为"special“的所有元素的样式,可以使用经典的for循环:
var x = document.getElementsByClassName("special");
for (var i=0; i<x.length; i++) {
x[i].style.color = "blue";
}https://stackoverflow.com/questions/45699821
复制相似问题