Manipulating style with getElementsByClassName

后端 未结 5 1106
名媛妹妹
名媛妹妹 2021-01-27 10:25

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.

I am an h1!<

5条回答
  •  长情又很酷
    2021-01-27 11:02

    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
    .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;
    }
    a b

    I am an h1!

    Hello

    Goodbye

    Hi Again

    Goodbye Again

提交回复
热议问题