首页  >  问答  >  正文

"为什么style.backgroundColor没有效果?"

<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粉969253139P粉969253139422 天前499

全部回复(2)我来回复

  • P粉593536104

    P粉5935361042023-08-25 13:03:07

    你的代码无法工作,因为当你的代码首次运行时,style属性没有设置backgroundColorstyle代表元素的内联样式属性,而你的元素在开始时没有内联样式。当你检查元素的背景是否为redgray时,它既不是红色也不是灰色,因为它没有内联样式(style.backgroundColor实际上是空字符串)。

    你有几个选择:

    • 使用getComputedStyle来查看元素的background-color,无论它是否内联设置。
    • 提供一个默认情况,无论元素是否已经设置,都会设置元素的background-color。(如果是红色,将其切换为灰色;否则,将其设置为红色。)

    任何一种方法都可以实现你的需求,这取决于你在解决方案中需要多大的灵活性,我将留给你决定。

    回复
    0
  • P粉239164234

    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>

    回复
    0
  • 取消回复