簡體   English   中英

改變 a 的背景顏色<tr>點擊

[英]Changing the background color of a <tr> on click

我試圖在單擊元素時更改元素的背景顏色。 基本上,我希望能夠在每次單擊時來回切換此顏色。

這是我正在使用的代碼:

        function activateButton1() {
            var x = document.getElementById('postButton1');

            if (x.className == 'postButton1') {
                x.className = 'postButton1on';
            } else {
                x.className = 'postButton1';
            }
        }

我正在使用兩個具有不同背景顏色的不同 CSS 類,但它不起作用。 任何人都可以提供任何見解嗎?

這可以通過toggle方法完成:

function activateButton1() {
    this.classList.toggle("postButton1on");
}

您甚至可以在 html 中觸發它以簡化事情:

<tr onclick="this.classList.toggle('postButton1on')">...</tr>

然后只要.postButton1on css 在.postButton1 css 之后聲明,那么.postButton1on背景顏色就會覆蓋之前設置的內容。

使用 jQuery,您可以通過

$( "#postButton1" ).on('click', function(){
  $( this ).toggleClass( "postButton1on" );
};

可能無法正常工作,因為您可能混合使用idclass ,因為它們具有相同的名稱,至少在您發布的 JS 中是這樣。 這是打包在 HTML 文檔中的所有內容,經過測試可以正常工作:

<!DOCTYPE html>
<html>
<head>
  <style>
    .off {
      background-color: white;
    }
    .on {
      background-color: red;
    }
  </style>
  <script>
    function change() {
      var x = document.getElementById('post');
      if (x.className.match('on')) {
        x.className = 'off';
      } else {
        x.className = 'on';
      }
    }
    function change2() {
      var x = document.getElementById('row');
      if (x.className.match('on')) {
        x.className = 'off';
      } else {
        x.className = 'on';
      }
    }
  </script>
</head>
<body>
  <button id="post" onclick="change()" class="on">hello</button>
  <table>
    <tr id="row" onclick="change2()" class="on">
      <td>hey</td>
      <td>hey</td>
    </tr>
  </table>
</body>
</html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM