我有自定义复选框,我的样式类似于按钮。当您单击标签或输入时,它周围的 div 会改变颜色。但是,只有标签和输入是可点击的。
有没有办法让整个 div/按钮都可以点击(即边框内的所有内容)?
这是我的代码:
div.label {
border:solid 1px gray;
line-height:40px;
height:40px;
width: 250px;
border-radius:40px;
-webkit-font-smoothing: antialiased;
margin-top:10px;
font-family:Arial,Helvetica,sans-serif;
color:gray;
text-align:center;
}
label {
display:inline;
text-align:center;
}
input[type=checkbox] {
display: none;
}
input:checked + div {
border: solid 1px red;
color: #F00;
}
input:checked + div:before {
content: "\2713";
}
<input id="lists[Travel]" type="checkbox" name="lists[Travel]" />
<div class="label">
<label for="lists[Travel]">Travel</label> <br>
</div>
最佳答案
答案很简单:您不需要额外的 div
-元素。实际上你可以放置一个 label
- 任何你想要的元素并将它与 input
相关联-您选择的元素。
您可以通过提供 input
-元素a id
-属性并关联 label
-具有相应 for
的元素-属性。
例如:<input id="my-input-id">[...]<label for="my-input-id">Label Text</label>
)
- A
<label>
can be associated with a control either by placing the control element inside the element, or by using thefor
attribute. Such a control is called the labeled control of the label element. One input can be associated with multiple labels.- Labels are not themselves directly associated with forms. They are only indirectly associated with forms through the controls with which they're associated.
- When a
<label>
is clicked or tapped, and it is associated with a form control, the resultingclick
event is also raised for the associated control.
来源:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label
label {
display:block;
border:solid 1px gray;
line-height:40px;
height:40px;
width: 250px;
border-radius:40px;
-webkit-font-smoothing: antialiased;
margin-top:10px;
font-family:Arial,Helvetica,sans-serif;
color:gray;
text-align:center;
}
input[type=checkbox] {
display: none;
}
input:checked + label {
border: solid 1px red;
color: #F00;
}
input:checked + label:before {
content: "\2713 ";
}
/* new stuff */
.check {
visibility: hidden;
}
input:checked + label .check {
visibility: visible;
}
input.checkbox:checked + label:before {
content: "";
}
<input id="lists[Travel]" type="checkbox" name="lists[Travel]" />
<label for="lists[Travel]">Travel with jump</label>
<!-- alternatively avoid jumps between text of state checked and unchecked -->
<input class="checkbox" id="lists[new]" type="checkbox" name="lists[new]" />
<label for="lists[new]"><span class="check">✓</span> Travel without jump</label>
此外,您还可以摆弄 display: block
的 <label>
.
但这应该很简单,给它 float: left
, display: inline-block
或任何使所需元素 float 的方法。
关于html - 如何使整个自定义复选框/Div 可点击——而不仅仅是标签 + 输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25319599/