"為什麼style.backgroundColor沒有效果?"
P粉969253139
2023-08-24 16:47:18
<p>嘗試透過點擊儲存格來改變儲存格的顏色。 </p>
<p>儲存格通常為灰色,第一次點擊時應變為紅色。當我點擊紅色單元格時,它應該再次變為灰色。 </p>
<p><br /></p>
<pre class="brush:js;toolbar:false;">function changeColor(cell) {
var red = '#FE2E2E';
var grey = '#E6E6E6';
if (cell.style.backgroundColor == grey) {
cell.style.backgroundColor = red;
} else {
if (cell.style.backgroundColor == red) {
cell.style.backgroundColor = grey;
}
};
};</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>我還試了<code>.style.bgColor</code>,<code>rgb</code>和<code>if (cell.style.backgroundColor ===</code> ,但這些也沒有起作用。單元格背景顏色的值要么是通過<em>.backgroundColor</em>:<strong>''</strong>,要么是通過<em>.bgColor< /em>:<strong>undefined</strong>。</p>
你的程式碼無法運作,因為當你的程式碼首次運行時,
style
屬性沒有設定backgroundColor
:style
代表元素的內聯樣式屬性,而你的元素在開始時沒有內聯樣式。當你檢查元素的背景是否為red
或gray
時,它既不是紅色也不是灰色,因為它沒有內聯樣式(style.backgroundColor
實際上是空字串)。你有幾個選擇:
getComputedStyle
來查看元素的background-color
,無論它是否內聯設定。background-color
。 (如果是紅色,將其切換為灰色;否則,將其設為紅色。)任何一種方法都可以實現你的需求,這取決於你在解決方案中需要多大的靈活性,我將留給你決定。
從
style.backgroundColor
取得的值可能不會以與設定時相同的格式傳回;它以瀏覽器想要的任何格式呈現。一種最小更改的方法是在元素上儲存一個標誌(參見註釋):