如何通过单击标签来防止选择单选按钮

How to prevent radio buttons being selected by clicking their labels

我有一组单选按钮,每个按钮都有自己的标签。标签宽度设置为自动,这是我想要的,因为将来文本长度可能会增加。

目前,如果我单击标签,它将 select 相应的单选按钮。据我了解,这是默认的 HTML 行为。是否有任何简单的(简单的我的意思是最好不使用 Javascript)方法来抑制这种默认行为?这样我就可以 select 单选按钮只能通过单击灰色圆圈本身吗?

为了改变这种行为,您首先需要了解如何将 checkbox/radio 元素与 <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>元素时选中radio元素:

<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>