"為什麼style.backgroundColor沒有效果?"
P粉969253139
P粉969253139 2023-08-24 16:47:18
0
2
492
<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>
P粉969253139
P粉969253139

全部回覆(2)
P粉593536104

你的程式碼無法運作,因為當你的程式碼首次運行時,style屬性沒有設定backgroundColorstyle代表元素的內聯樣式屬性,而你的元素在開始時沒有內聯樣式。當你檢查元素的背景是否為redgray時,它既不是紅色也不是灰色,因為它沒有內聯樣式(style.backgroundColor實際上是空字串)。

你有幾個選擇:

  • 使用getComputedStyle來查看元素的background-color,無論它是否內聯設定。
  • 提供一個預設情況,無論元素是否已經設置,都會設定元素的background-color。 (如果是紅色,將其切換為灰色;否則,將其設為紅色。)

任何一種方法都可以實現你的需求,這取決於你在解決方案中需要多大的靈活性,我將留給你決定。

P粉239164234

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>
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!