2015-03-31 35 views
0

嘗試製作一個功能,當您點擊「r」時切換不同背景顏色的類。如果它的綠色,它會變黃,如果它的黃色變成紅色等等。但是我並沒有真正把它變成工作。什麼是實現這一目標的最佳方法?在多種顏色之間切換,用javascript

嘗試過這樣的事情:

var shape1 = document.getElementById("shape1"); 

    //toggle between colors on keydown "r". 
    function changeColor (event) { 
    var key = event.keyCode; 

    if (key === 82 && shape1.className.match(/(?:^|\s)green(?!\S)/)) { 
     shape1.classList.toggle('yellow'); 
    } 
    if (key === 82 && shape1.className.match(/(?:^|\s)yellow(?!\S)/)) { 
     shape1.classList.toggle('red'); 
    } 
    if (key === 82 && shape1.className.match(/(?:^|\s)red(?!\S)/)) { 
     shape1.classList.toggle('blue'); 
    } 
    if (key === 82 && shape1.className.match(/(?:^|\s)blue(?!\S)/)) { 
     shape1.classList.toggle('green'); 
    } 
    } 
    document.addEventListener("keydown", changeColor, false); 

但是,是的..它不是一個真正的工作了。假設切換不是正確的做法。 的jsfiddle示範: https://jsfiddle.net/rbf10qjn/

+1

以及你可能需要刪除舊的,因爲你使用classList,爲什麼你不使用contains()? – epascarello 2015-03-31 15:19:45

回答

0

首先擺脫其用完全相同的名字作爲ID創建變量混淆解釋的第一線。那是幹什麼用的?

var shape1 = document.getElementById("shape1"); 

既然你知道這個名字就直接使用這個ID!

其次,你的方法是錯誤的。而不是addEventListener使用像這樣的方法...

document.onkeydown=function(e){ 

if ((e.keyCode===82) && (shape1.style.backgroundColor=='green')) {shape1.style.backgroundColor='yellow';} else 
if ((e.keyCode===82) && (shape1.style.backgroundColor=='yellow')) {shape1.style.backgroundColor='red';} else 
if ((e.keyCode===82) && (shape1.style.backgroundColor=='red')) {shape1.style.backgroundColor='blue';} 

etc... etc 

} 
+0

是的,的確如此。謝謝。 雖然我還不確定if語句應該如何。 – qua1ity 2015-03-31 16:14:12

+0

我編輯了上面的代碼以循環顯示顏色。我希望它可以。 – user4723924 2015-03-31 16:24:26

+0

謝謝,但它似乎仍然無法正常工作。檢查https://jsfiddle.net/o5ct1r6a/1/ – qua1ity 2015-03-31 17:38:55

相關問題