P粉5935361042023-08-25 13:03:07
Your code doesn't work because the style
attribute is not set when your code first runs backgroundColor
: style
represents the inline style attribute of the element , and your element has no inline styles at the beginning. When you check if the element's background is red
or gray
, it's neither red nor gray because it doesn't have an inline style (style.backgroundColor
actually is an empty string).
You have several choices:
getComputedStyle
to see the background-color
of an element, whether or not it is set inline. background-color
will be set regardless of whether the element has been set. (If it's red, switch it to gray; otherwise, set it to red.) Either approach can achieve what you need, depending on how much flexibility you need in your solution, I'll leave it to you to decide.
P粉2391642342023-08-25 12:44:41
The value obtained from style.backgroundColor
may not be returned in the same format as when set; it is rendered in whatever format the browser expects.
A minimally changing approach is to store a flag on the element (see comments):
function changeColor(cell) { var red = '#FE2E2E'; var grey = '#E6E6E6'; // 获取标志;如果不存在,则为假值 var flag = cell.getAttribute("data-grey"); if (!flag) { // 变为灰色 cell.setAttribute("data-grey", "true"); cell.style.backgroundColor = red; } else { // 不是灰色,变为红色 cell.setAttribute("data-grey", ""); // 空值为假值 cell.style.backgroundColor = grey; } }
#table tr td { width: 20px; height: 50px; cursor: pointer; background-color: #E6E6E6; border: 1px solid black; }
<table class="table table-bordered" id="table"> <tbody> <tr> <td onclick="changeColor(this)"></td> <td onclick="changeColor(this)"></td> <td onclick="changeColor(this)"></td> <td onclick="changeColor(this)"></td> <td onclick="changeColor(this)"></td> </tr> </tbody> </table>