"Why does style.backgroundColor have no effect?"
P粉969253139
2023-08-24 16:47:18
<p>Try changing the color of a cell by clicking on it. </p>
<p>The cell is usually gray and should turn red when clicked for the first time. When I click on the red cell it should turn gray again. </p>
<p><br /></p>
<pre class="brush:js;toolbar:false;">function changeColor(cell) {
var red = '#FE2E2E';
var gray = '#E6E6E6';
if (cell.style.backgroundColor == gray) {
cell.style.backgroundColor = red;
} else {
if (cell.style.backgroundColor == red) {
cell.style.backgroundColor = gray;
}
};
};</pre>
<pre class="brush:css;toolbar:false;">#table tr td {
width: 20px;
height: 50px;
cursor: pointer;
background-color: #E6E6E6;
border: 1px solid black;
}</pre>
<pre class="brush:html;toolbar:false;"><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></pre>
<p><br /></p>
<p>I also tried <code>.style.bgColor</code>, <code>rgb</code> and <code>if (cell.style.backgroundColor ===</code> , but these didn't work either. The value for the cell background color was either passed in <em>.backgroundColor</em>:<strong>''</strong> or passed in <em>.bgColor< /em>:<strong>undefined</strong>.</p>
Your code doesn't work because the
style
attribute is not set when your code first runsbackgroundColor
: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 isred
orgray
, 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 thebackground-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.
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):