2015-03-31 33 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

相关问题