如何为第一次选择和第二次选择复选框应用不同的颜色

how to apply different colors for first select and second select checkbox

本文关键字:选择 应用 颜色 复选框 第二次 第一次      更新时间:2023-09-26

我想为第一个和第二个复选框应用不同的颜色,第一个复选框应该是绿色,第二个应该是红色。如果用户取消选中绿色,下一个应该是绿色。如果用户未选中红色,则表示下一个复选框应为红色。请帮帮我。

<script class="jsbin" src="jquery.min.js"></script>
<style>
  article, aside, figure, footer, header, hgroup, 
  menu, nav, section { display: block; }
</style>
<body>
<form name="disc">
  <p>Select Only Two</p>
  <input type="checkbox" id="ad"/>
  <input type="checkbox" id="ai"/>
  <input type="checkbox" id="as"/>
  <input type="checkbox" id="ac"/>
</form>
<script>
  $("form").on("click", ":checkbox", function(event){
  $(":checkbox:not(:checked)", this.form).prop("disabled", function(){
    return $(this.form).find(":checkbox:checked").length == 2;
  });
  });
</script>

试试这个JSFiddle演示

JS:

$(function() {
$('input[type=checkbox]').each(function() {
    var span = $('<span class="' + $(this).attr('type') + ' ' + $(this).attr('class') + '"></span>').click(doCheck).mousedown(doDown).mouseup(doUp);
    if ($(this).is(':checked')) {
        span.addClass('checked');
    }
    $(this).wrap(span).hide();
});
function doCheck() {
    if ($(this).hasClass('checked')) {
        if($('#disc').find(":checkbox:checked").length >= 1) {
            $(this).removeClass('checked');
            $(this).removeClass('red');
            $(this).removeClass('green');
            $(this).addClass('default');
            $(this).children().prop("checked", false);
        }
    } else {
        console.log($('#disc').find(":checkbox:checked").length);
        if($('#disc').find(":checkbox:checked").length < 2) {
            $(this).addClass('checked');
            $(this).removeClass('default');
            if($('#disc').find(":checkbox:checked").length < 1) {
                $(this).addClass('green');
            } else {
                    $(this).addClass('red');
            }
            $(this).children().prop("checked", true);
        }
    }
}
function doDown() {
    $(this).addClass('clicked');
}
function doUp() {
    $(this).removeClass('clicked');
}
});

CSS:

.checkbox, .radio {
width: 19px;
height: 20px;
padding: 0px;
background: url("http://i48.tinypic.com/raz13m.jpg");
display: block;
clear: left;
float: left;
}
.checked {
 background-position: 0px -50px;   
}
.clicked {
 background-position: 0px -25px;
}
.clicked.checked {
 background-position: 0px -75px;
}

.green {
background-color: green;
}
.red {
background-color: red;
}
.default {
background-color: none;
}

希望这就是你想要的。

附言:这是我对CSS样式复选框中接受的fiddle所做的一个轻微修改,因此背景着色归功于原作者Jeff B