jQuery如果已选中复选框,然后更改背景颜色

时间:2019-05-21 14:16:18

标签: javascript jquery html css3

如果选中该复选框,则如何更改背景颜色。

HTML

 <input type="checkbox" name="somename" id="thisid" checked="checked">

jQuery

 if ($("input[type=checkbox]").is(':checked')){
       $("input[type=checkbox]").css('background','red');
   }

理想的做法是在加载时更改背景颜色。有人可以帮我吗?

3 个答案:

答案 0 :(得分:0)

您的代码很好。这很可能在加载时不起作用,因为您尚未将代码包装在“就绪”函数中。然后,要更改选中的复选框的背景颜色,您需要将CSS链接到查询中。

// this wrapper waits until the DOM has loaded before executing the code inside
$(function() {
  $("input[type=checkbox]:checked").css('background-color', 'red')
})

如果您期望在切换复选框时背景颜色会发生变化,那么您还需要设置一个事件。

// this wrapper waits until the DOM has loaded before executing the code inside
$(function() {
  var checkboxes = $("input[type=checkbox]")

  // set the styles based on the initial state on load
  checkboxes.is(':checked').css('background-color', 'red')

  // update the styles as the checkbox states are changed
  checkboxes.on('change', function() {
    var checkbox = $(this)

    checkbox.css('background-color', checkbox.is(':checked') ? 'red' : 'transparent'))
  })
})
input[type='checkbox'] {
  -webkit-appearance: none; /* necessary to override checkbox styles on OSX and iOS */
  width: 20px;
  height: 20px;
  background: grey;
}

input[type='checkbox']:checked {
  background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="checkbox">
<input type="checkbox" checked>
<input type="checkbox">
<input type="checkbox" checked>
<input type="checkbox">

注意:在iOS和OSX上的许多浏览器中,复选框和收音机均具有硬编码样式。为了明确地覆盖它,您需要使用appearance: none(对于Chrome和Safari,在这种情况下为-webkit-appearance)来允许您的样式覆盖浏览器的默认设置。

答案 1 :(得分:0)

如果要根据是否选中复选框(或相关标签)设置样式,可以使用CSS伪类:checked

input[type=checkbox] {
    /** Style for unchecked **/

} 
input[type=checkbox]:checked {
    /** Style for checked **/
} 

但是,浏览器中的复选框通常无法通过这种方式进行样式设置。您必须将它们替换为伪复选框,即自定义元素,它们看起来像一个复选框,而隐藏了实际的复选框。

也许看看here

答案 2 :(得分:0)

请确保一旦dom准备好就可以进行操作。只需遍历它们并检查。

$(function() {
    $("input[type=checkbox]").each({
        if($(this).is(':checked')) {
            $(this).css('background-color', 'red');
         }
    });
})