尝试重复单击功能

时间:2019-02-28 01:52:04

标签: javascript

我正在尝试为两个玩家制作井字游戏。在游戏旁边的一个小窗口中,P1P2旁边有灯。 P1light以绿色开始,而P2light以红色开始。单击任何正方形时,它将翻转颜色,因此P1light为红色,P2Light为绿色。在单击另一个正方形后,它应该再次切换,但是没有。这是我的函数代码。我尝试了while循环和for循环,但似乎没有用。

var x; // just so I can refer to the function as true or false

function switcher(){
    if (p1Light.style.backgroundColor = "#5fd81e"){
        p2Light.style.backgroundColor = "#5fd81e";
        p1Light.style.backgroundColor = "#ce2e1c";
        x = true;
    }else {
        x = false;
    };
};

function switcher2(){
    if (p2Light.style.backgroundColor = "#5fd81e"){
        p2Light.style.backgroundColor = "#ce2e1c";
        p1Light.style.backgroundColor = "#5fd81e";
        x = false;
    } else {
        x = true;
    };
};

3 个答案:

答案 0 :(得分:2)

这不仅可以解决问题。我对其进行了优化,以便您只能使用一个功能switcher()来为每个玩家的回合切换颜色。我也知道您的x是当前玩家的回合。如果我弄错了,请随时进行调整或通知我进行修复。

const styleGreen = "#5fd81e"
const styleRed = "#ce2e1c"
let playerTurn = 1  // Starts from player 1

switcher = () => {
  // Player 1's turn
  if (playerTurn % 2 === 1) {
    p1Light.style.backgroundColor = styleGreen
    p2Light.style.backgroundColor = styleRed
  }
  // Player 2's turn
  else {
    p2Light.style.backgroundColor = styleGreen
    p1Light.style.backgroundColor = styleRed
  }
  playerTurn++
}
<div id="p1Light">1</div>
<div id="p2Light">2</div>
<button onclick="switcher()">Switch Turn</button>

答案 1 :(得分:2)

style.backgroundColor仅在直接定义属性后才能获取颜色。它还会返回rgb颜色代码!因此,需要使用getComputedStyle并比较颜色,您需要创建额外的元素以临时设置比较颜色。

var x; // just so I can refer to the function as true or false

function tempColor(color) {
  var ele = document.createElment("span");
  ele.setAttribute("id","temp_color");
  ele.style.display = "none";
  ele.style.color = color;
  document.body.appendChild(ele);
  return document.defaultView.getComputedStyle(temp_color).color;
}

function switcher(){
    var p1Color = document.defaultView.getComputedStyle(p1Light).backgroundColor;
    var compareColor = tempColor("#5fd81e");
    if (p1Color == compareColor){
        p2Light.style.backgroundColor = "#5fd81e";
        p1Light.style.backgroundColor = "#ce2e1c";
        x = true;
    }else {
        x = false;
    };
    temp_color.remove(); //remove temp element 
};

function switcher2(){
    var p2Color = document.defaultView.getComputedStyle(p2Light).backgroundColor;
    var compareColor = tempColor("#5fd81e");
    if (p2Color == compareColor){
        p2Light.style.backgroundColor = "#ce2e1c";
        p1Light.style.backgroundColor = "#5fd81e";
        x = false;
    } else {
        x = true;
    };
    temp_color.remove(); //remove temp element 
};

答案 2 :(得分:1)

您在p1Light.style.backgroundColor条件下不小心分配了p2Light.style.backgroundColorif。这将产生意外的结果(该语句始终为true)。

switcher()中的错字:

if(p1Light.style.backgroundColor = "#5fd81e")

应为:

if(p1Light.style.backgroundColor === "#5fd81e")

switcher2()中的错字:

if (p2Light.style.backgroundColor = "#5fd81e"){

应为:

if (p2Light.style.backgroundColor === "#5fd81e"){

希望这会有所帮助,