【发布时间】:2016-02-12 18:06:19
【问题描述】:
我有一组单选按钮,每个按钮都有自己的标签。标签宽度设置为自动,这是我想要的,因为将来文本长度可能会增加。
目前,如果我单击标签,它将选择相应的单选按钮。据我了解,这是默认的 HTML 行为。是否有任何简单的(简单的意思是最好不使用 Javascript)来抑制这种默认行为?这样我只能通过单击灰色圆圈本身来选择单选按钮?
【问题讨论】:
标签: html radio-button label
我有一组单选按钮,每个按钮都有自己的标签。标签宽度设置为自动,这是我想要的,因为将来文本长度可能会增加。
目前,如果我单击标签,它将选择相应的单选按钮。据我了解,这是默认的 HTML 行为。是否有任何简单的(简单的意思是最好不使用 Javascript)来抑制这种默认行为?这样我只能通过单击灰色圆圈本身来选择单选按钮?
【问题讨论】:
标签: html radio-button label
为了改变这种行为,您首先需要了解如何将复选框/单选元素与<label> 相关联。如果您理解这一点,那么您可以确保<input> 元素不与<label> 元素关联,以防止它被选中。
主要有两种方式:
<label> 元素包裹<input> 元素,以便隐式关联这些元素:<p>Wrapping the input elements with a label will cause the input element to be selected when clicking on the label.</p>
<label>
<input type="radio" name="confirm" />Initial Decision
</label>
<label>
<input type="radio" name="confirm" />Confirmation
</label>
<input> 元素的id 与<label> 元素的for 属性关联以显式关联元素:<p>If the input element's id matches the label element's for attribute, then clicking on a label element will select the corresponding input element:</p>
<input type="radio" id="initial" name="confirm" />
<label for="initial">Initial Decision</label>
<input type="radio" id="confirm" name="confirm" />
<label for="confirm">Confirmation</label>
因此,您可以通过简单地不关联元素来有效地防止单击<label>元素时选择单选元素:
<input type="radio" name="confirm" />
<label>Initial Decision</label>
<input type="radio" name="confirm" />
<label>Confirmation</label>
【讨论】:
使用这段代码:
.lbl-ungroup {overflow:hidden; position:relative; }
.lbl-ungroup:after {content:" ";position:absolute; height:100%;width:100%;left:0;}
.lbl-ungroup label input[type=radio] {position:relative; z-index:1;}
<style>
.lbl-ungroup {overflow:hidden; position:relative; }
.lbl-ungroup:after {content:" ";position:absolute; height:100%;width:100%;left:0;}
.lbl-ungroup label input[type=radio] {position:relative; z-index:1;}
</style>
<div class="lbl-ungroup">
<label><input type="radio" name="rbtgroup"> Male</label>
<label><input type="radio" name="rbtgroup"> Female</label>
<label><input type="radio" name="rbtgroup"> Other</label>
</div>
【讨论】: