单击后闪烁行或在表格单元格中切换

时间:2017-12-11 21:05:59

标签: javascript html css

按照answer的示例处理一些javascript代码。但不知何故,单击它后不会重复颜色。任何人都可以指导我如何处理这个问题? (原谅非英语标识符)

HTML代码为:

<html>
    <head>
        <title></title>
        <script src="lab5_2.js"></script>
        <link rel="stylesheet" type="text/css" href="lab5_2.css">
    </head>
    <body>
        <div id="result"></div>
        <p id="vlerat"></p>
    </body>
</html>

CSS代码是:

td {width: 100px; height: 100px; background: blue;}

Javascript代码是:

var tableResult;

function start() {

    tableResult = "<table border='1' align='center'>";

    for (var i = 1; i <= 5; i++) {
        tableResult += "<tr>";

        for (var j = 1; j <= 5; j++) {
            tableResult += "<td id='" + i + j + "' onclick='save(id)'></td>"
        }
        tableResult += "</tr><br>";
    }
    tableResult += "</table>";

    document.getElementById("result").innerHTML = tableResult;
}

function changeColor(test) {
    var flag = true;
    if (flag === true) {
        document.getElementById(test).style.background = "#ff0000";
        flag = false;
    } else if (flag === false) {
        document.getElementById(test).style.background = "#ffff00";
        flag = true;
    }
}

function save(id) {
    setInterval(changeColor(id), 110);
}

window.addEventListener("load", start, false);

1 个答案:

答案 0 :(得分:0)

问题是flag is getting initialized as true again and again一进入该功能。只调用了这部分代码:

if (flag === true) {
    document.getElementById(test).style.background = "#ff0000";
    flag = false;
  }

这就是为什么颜色会变成红色。为了解决这个问题,只需要declare it out of the function进行修复就可以了。希望,它有所帮助。

&#13;
&#13;
var tableResult;
var flag = true;

function start() {

  tableResult = "<table border='1' align='center'>";

  for (var i = 1; i <= 5; i++) {
    tableResult += "<tr>";

    for (var j = 1; j <= 5; j++) {
      tableResult += "<td id='" + i + j + "' onclick='save(id)'></td>"
    }
    tableResult += "</tr><br>";
  }
  tableResult += "</table>";

  document.getElementById("result").innerHTML = tableResult;
}

function changeColor(test) {

  if (flag === true) {
    document.getElementById(test).className += "color";
  }

}


function save(id) {
  setInterval(changeColor(id), 110);
}

window.addEventListener("load", start, false);
&#13;
td {
  width: 100px;
  height: 100px;
  background: blue;
}

.color {
  animation: colorchange 3s infinite;
}

@keyframes colorchange {
  0% {
    background: red;
  }
  50% {
    background: yellow;
  }
  100% {
    background: blue;
  }
}
&#13;
<div id="result"></div>
<p id="vlerat"></p>
&#13;
&#13;
&#13;