P粉5935361042023-08-25 13:03:07
你的程式碼無法運作,因為當你的程式碼首次運行時,style
屬性沒有設定backgroundColor
: style
代表元素的內聯樣式屬性,而你的元素在開始時沒有內聯樣式。當你檢查元素的背景是否為red
或gray
時,它既不是紅色也不是灰色,因為它沒有內聯樣式(style.backgroundColor
實際上是空字串)。
你有幾個選擇:
getComputedStyle
來查看元素的background-color
,無論它是否內聯設定。 background-color
。 (如果是紅色,將其切換為灰色;否則,將其設為紅色。)任何一種方法都可以實現你的需求,這取決於你在解決方案中需要多大的靈活性,我將留給你決定。
P粉2391642342023-08-25 12:44:41
從style.backgroundColor
取得的值可能不會以與設定時相同的格式傳回;它以瀏覽器想要的任何格式呈現。
一種最小更改的方法是在元素上儲存一個標誌(參見註釋):
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>