简体   繁体   中英

How do i change colors of two selected elements with css and javascript

I'm working on some simple game for browser and i have this problem.

This is my HTML/PHP: (just 1 line that is important for this)

    echo '<div id="div'.$n.'" class="d'.$rand.'" onclick="swapit(this.id, this.className)"></div>';

I've got 4 different class names that are generated randomly and for them i got 4 different colors. And I'm using id just to know what exact element that is 'cause there are 13x8 elements like this randomly generated. ID is not random, it is increasing - 0,1,2,3,4...

This is my CSS:

.d0 {
    width:60px;
    height:50px;
    border:0;
    margin:8px 0 0 7px;
    padding:0;
    background-color:#0080FF;
    position:relative;
    float:left;
    cursor:pointer;
    box-shadow:0 0 1px #0080FF;
    border-radius:5px;
}

I've also defined d1,d2 and d3 but with different background colors. Id's are not defined anywhere in my css file.

And this is part of my JAVASCRIPT:

function swapit(id, classn)
{
    if(n == 0)
    {
        div1 = document.getElementById(id);
        color1 = document.getElementsByClassName(classn)[0].style.backgroundColor;      
        //alert(color1);
        //when i alert color1 it is blank       
        n++;
    }
    else
    {
        document.getElementById(id).style.backgroundColor = color1;
        div1.style.backgroundColor = document.getElementsByClassName(classn)[0].style.backgroundColor;
        n--;
    }
}

What I want is when i click on some blue div and then on some green div.. I want blue to become green and green to become blue. But it seems that I'm missing something with that style.backgroundColor property.. 'cause it doesn't return anything.

So please, help me :)

You should use getComputedStyle to get the styles applied via stylesheets:

// ...
var $el = document.getElementsByClassName(classn)[0];
alert(getComputedStyle($el).backgroundColor); 
// ...

See these two for further discussion about usage in different browsers:

  1. getComputedStyle in pure Javascript?
  2. http://caniuse.com/#feat=getcomputedstyle

Thank you for all your answers, I just found one other solution that fixes all my problems.

function swapit(id, classn)
{
    if(n == 0)
    {
        div1 = id;
        class1 = classn;
        n = 1;
    }
    else
    {
        document.getElementById(id).setAttribute('class', class1);
        document.getElementById(div1).setAttribute('class', classn);
        n = 0;
    }   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM