使用method 1 to create a clickable label,hiding the checkbox with CSS和toggling it and the label with jQuery,我得到了这个:
$('label').click(function(e) {
$(this).toggleClass('active');
var cbx = $('input', this);
cbx.prop('checked', !cbx.prop("checked"));
console.log($('input', this).prop('checked'));
return false;
})
input[type="checkbox"] {visibility: hidden;position: absolute}
label {background-color: pink;border: 1px solid lightblue;padding: 20px}
label.active {background-color: lightgreen}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<input type="checkbox" checked />Check Button</label>
我的问题是:是否可以仅使用CSS 执行相同操作?
我意识到我正在使用<label>
而不是<button>
,我认为有更好的方法可以通过jQuery实现这一目标。如果您考虑回复一个,请使用复选框(或至少解释您不能使用它的原因)。
答案 0 :(得分:6)
尝试css伪代码:
input.chk-btn {
display: none;
}
input.chk-btn + label {
border: 1px solid grey;
background: ghoswhite;
padding: 5px 8px;
cursor: pointer;
border-radius: 5px;
}
input.chk-btn:not(:checked) + label:hover {
box-shadow: 0px 1px 3px;
}
input.chk-btn + label:active,
input.chk-btn:checked + label {
box-shadow: 0px 0px 3px inset;
background: #eee;
}
<input type="checkbox" id='c1' class='chk-btn' />
<label for='c1'>Check Button</label>
<input type="checkbox" id='c2' class='chk-btn' />
<label for='c2'>Toggle</label>
答案 1 :(得分:-1)
你可以这样做:
或试试这个:
<强> HTML 强>
<input type="checkbox" id="checkbox-1-1" class="regular-checkbox" /><label for="checkbox-1-1"></label>
<强> CSS 强>
.regular-checkbox { display:none; }
.regular-checkbox + label {
background-color: #fafafa;
border: 1px solid #cacece;
box-shadow: 0 1px 2px rgba(0,0,0,0.05), inset 0px -15px 10px -12px rgba(0,0,0,0.05);
padding: 9px;
border-radius: 3px;
display: inline-block;
position: relative;
}
.regular-checkbox + label:active, .regular-checkbox:checked + label:active {
box-shadow: 0 1px 2px rgba(0,0,0,0.05), inset 0px 1px 3px rgba(0,0,0,0.1);
}
.regular-checkbox:checked + label {
background-color: #e9ecee;
border: 1px solid #adb8c0;
box-shadow: 0 1px 2px rgba(0,0,0,0.05), inset 0px -15px 10px -12px rgba(0,0,0,0.05), inset 15px 10px -12px rgba(255,255,255,0.1);
color: #99a1a7;
}
.regular-checkbox:checked + label:after {
content: '\2714';
font-size: 14px;
position: absolute;
top: 0px;
left: 3px;
color: #99a1a7;
}