getElementsByClassName

getElementsByClassName

本文介绍了使用getElementsByClassName操纵样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么我无法在代码中操纵.special的样式。我确定这很简单,但是却无法正常工作。

I don't understand why I cannot manipulate the style of .special in my code. I'm sure it's something simple, but it's not working.

<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";


推荐答案

返回的集合不仅仅是一个对象。因此,您需要遍历它们并为其应用颜色。以下是带有鼠标事件的示例示例。

getElementsByClassName returns a collection not just one object. So you need to loop through them and apply the color to it. Below is a sample example with mouse events.

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>

这篇关于使用getElementsByClassName操纵样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 02:18