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



按照答案的例子处理一些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);

问题是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即可正常工作。希望,它有帮助。

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);
td {
width: 100px;
height: 100px;
background: blue;
}
.color {
animation: colorchange 3s infinite;
}
@keyframes colorchange {
0% {
background: red;
}
50% {
background: yellow;
}
100% {
background: blue;
}
}
<div id="result"></div>
<p id="vlerat"></p>

最新更新