【问题标题】:when checkbox is checked, change background color of div选中复选框时,更改 div 的背景颜色
【发布时间】:2022-12-18 08:13:38
【问题描述】:

我想做的是当复选框被选中时,更改 div 的背景颜色,当它未被选中时,删除背景颜色。我怎样才能使用 jquery 做到这一点?

<div class="checkbox-container">
    <input type="checkbox" class ="checkbox-border" id="personal-info-checkbox">
      <label for="personal-info-checkbox"> Mark as reviewed and acknowledged
      </label>
 </div>

使用父选择器和 .removeclass 我不知道如何选择我的 div 并使用 jquery 关闭和打开颜色。

【问题讨论】:

  • 为了自己解决这个问题,您尝试了什么?你的(相关)在哪里“minimal reproducible example" 代码?该代码出了什么问题 - 以什么方式出现问题,是否报告了任何错误?
  • 为了给你一个开始看的方向,你需要在你的复选框上设置一个事件侦听器,因为使用 jQuery,你可以在你的容器元素上使用 toggleClass() 方法:api.jquery.com/toggleclass

标签: javascript html jquery css checkbox


【解决方案1】:

input 添加一个change 事件侦听器,根据是否选中设置其最近的父项div 的背景颜色:

$('input[type="checkbox"]').change(function(){
  $(this).closest('div').css('background-color', this.checked ? 'green' : 'white')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="checkbox-container">
    <input type="checkbox" class ="checkbox-border" id="personal-info-checkbox">
      <label for="personal-info-checkbox"> Mark as reviewed and acknowledged
      </label>
 </div>

【讨论】:

    【解决方案2】:

    试试这个我希望这对你有帮助

    <!DOCTYPE html>
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
      $("#personal-info-checkbox").click(function(){
        if($(this).is(":checked")){
            $(this).parent().addClass("color-blue");
        }else {
            $(this).parent().removeClass("color-blue");
        }
      });
    });
    </script>
    <style>
     .checkbox-container
     {
         padding:20px;
     }
     .color-blue {
         background-color:blue;
     }
    
    </style>
    </head>
    <body>
    
    <div class="checkbox-container">
        <input type="checkbox" class ="checkbox-border" id="personal-info-checkbox">
          <label for="personal-info-checkbox"> Mark as reviewed and acknowledged
          </label>
     </div>
    
    </body>
    </html>

    【讨论】:

      【解决方案3】:

      这是您如何执行此操作的示例

      $(function() {
        $("input[type=checkbox]").click( () => {
          $("div").toggleClass("background");
        })
      });
      .background {
        background: blue;
      }
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <div style="height:4em;">
      Change colors<input type="checkbox" />
      </div>

      【讨论】:

        【解决方案4】:

        有多种方法可以做到这一点:

        1. CSS(在撰写本文时,浏览器支持有限),
        2. jQuery(以及其他库),以及
        3. 原生 JavaScript。

          下面的例子在代码中有解释性的 cmets:

          // using jQuery, we select the relevant element via its class, and use the on()
          // method to bind the anonymous function as the event-handler for the 'change'
          // event:
          $('.checkbox-container.with-jQuery').on('change', function(){
            // here we find the <input> element descendant with find(), and then use the
            // is() method to test that element to see if it matches the :checked pseudo-
            // class; this returns a Boolean true/false which is cached in the 'checked'
            // variable:
              let checked = $(this).find('input').is(':checked');
            
            // here we use toggleClass() to toggle the 'checked' class-name on the element,
            // and use the 'checked' variable to ascertain whether the class should be
            // added/retained (if the Boolean is true) or removed/not-added (if the Boolean
            // is false):
              $(this).toggleClass('checked', checked);
          });
          
          
          // using JavaScript we use document.querySelector to retrieve the element
          // with the listed classes; and use EventTarget.addEventListener() to bind the
          // anonymous Arrow function as the event-handler for the 'change' event:
          document.querySelector('.with-JavaScript.checkbox-container').addEventListener('change',(evt)=>{
            // we cache a reference to the current element (the <div>):
              let current = evt.currentTarget,
                // we find the <input> descendant, and access its checked property to
                // obtain a Boolean true (if checked) or false (if not-checked) and
                // store that Boolean in the 'checked' variable:
                  checked = current.querySelector('input').checked;
            // here we use HTMLElement.classList.add() to add the 'active' class-name,
            // with the checked variable to determine if it should be added/retained
            // (if true) or removed/not-added (if false):
              current.classList.add('active', checked);
          });
          :root {
            --checkedColor: lime;
          }
          
          /* here we select the element via classes, and use :has()
             to check if it has a descendant element which matches
             the enclosed selector: */
          .with-CSS.checkbox-container:has(input:checked) {
            /* if so, we set the --checkedColor custom property
               as the background-color of the element: */
            background-color: var(--checkedColor);
          }
          
          .with-jQuery.checkbox-container.checked {
            background-color: var(--checkedColor);
          }
          
          .with-JavaScript.checkbox-container.active {
            background-color: var(--checkedColor);
          }
          <!-- each wrapper <div> has a 'with-...' class applied in order to identify which
               approach is being taken: -->
          <div class="checkbox-container with-CSS">
            <!-- an id must be unique, to that end - because there are three checkboxes in
                 this example - the id has been modified, as has the corresponding <label>
                 element's 'for' attribute: -->
            <input type="checkbox" class="checkbox-border" id="personal-info-checkbox1">
            <label for="personal-info-checkbox1"> Mark as reviewed and acknowledged
            </label>
          </div>
          
          <div class="checkbox-container with-jQuery">
            <input type="checkbox" class="checkbox-border" id="personal-info-checkbox2">
            <label for="personal-info-checkbox2"> Mark as reviewed and acknowledged
            </label>
          </div>
          
          <div class="checkbox-container with-JavaScript">
            <input type="checkbox" class="checkbox-border" id="personal-info-checkbox3">
            <label for="personal-info-checkbox3"> Mark as reviewed and acknowledged
            </label>
          </div>

        【讨论】:

          猜你喜欢
          • 2019-03-22
          • 2019-06-03
          • 1970-01-01
          • 1970-01-01
          • 2012-06-09
          • 1970-01-01
          • 2021-01-12
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多