【问题标题】:How to prevent radio buttons being selected by clicking their labels如何防止通过单击标签来选择单选按钮
【发布时间】:2016-02-12 18:06:19
【问题描述】:

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

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

【问题讨论】:

    标签: html radio-button label


    【解决方案1】:

    为了改变这种行为,您首先需要了解如何将复选框/单选元素与<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>
    • &lt;input&gt; 元素的id&lt;label&gt; 元素的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>

    因此,您可以通过简单地不关联元素来有效地防止单击&lt;label&gt;元素时选择单选元素:

    <input type="radio" name="confirm" />
    <label>Initial Decision</label>
    
    <input type="radio" name="confirm" />
    <label>Confirmation</label>

    【讨论】:

    • 有充分的理由将标签和单选按钮相关联——最值得注意的是,可访问性。更理想的解决方案不依赖于切断关联。
    • @JohnnyTisdale - 绝对。
    【解决方案2】:

    如何防止单选按钮通过点击标签被选中?

    使用这段代码:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-11
      • 1970-01-01
      • 2013-07-30
      • 2010-12-04
      • 2012-12-13
      • 2011-12-09
      • 1970-01-01
      相关资源
      最近更新 更多