簡體   English   中英

如何使用CSS和JavaScript更改兩個選定元素的顏色

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

我正在為瀏覽器開發一些簡單的游戲,但我遇到了這個問題。

這是我的HTML / PHP :(對此很重要的只有1行)

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

我有4種不同的類別名稱是隨機生成的,為此,我有4種不同的顏色。 我使用id只是為了知道確切的元素是因為存在13x8這樣的隨機生成的元素。 ID不是隨機的,而是在增加-0、1、2、3、4 ...

這是我的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;
}

我還定義了d1,d2和d3,但是具有不同的背景色。 在我的CSS文件中的任何地方都沒有定義ID。

這是我的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--;
    }
}

我想要的是當我單擊某個藍色div,然后單擊某個綠色div時。我希望藍色變成綠色,綠色變成藍色。 但似乎我缺少該style.backgroundColor屬性的內容。因為它不返回任何內容。

所以請幫我:)

您應該使用getComputedStyle來獲取通過樣式表應用的樣式:

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

有關在不同瀏覽器中使用情況的進一步討論,請參見以下兩個:

  1. 純Javascript中的getComputedStyle?
  2. http://caniuse.com/#feat=getcomputedstyle

感謝您的所有回答,我剛剛找到了另一種解決所有問題的解決方案。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM