程序go 2011-06-09 13:33 采纳率: 100%
浏览 653
已采纳

如何创建带有可点击标签的 HTML 复选框

How can I create an HTML checkbox with a label that is clickable (this means that clicking on the label turns the checkbox on/off)?

转载于:https://stackoverflow.com/questions/6293588/how-to-create-an-html-checkbox-with-a-clickable-label

  • 写回答

10条回答 默认 最新

  • 谁还没个明天 2011-06-09 13:36
    关注

    Method 1: Wrap Label Tag

    Wrap the checkbox within a label tag:

    <label><input type="checkbox" name="checkbox" value="value">Text</label>
    

    Method 2: Use the for Attribute

    Use the for attribute (match the checkbox id):

    <input type="checkbox" name="checkbox" id="checkbox_id" value="value">
    <label for="checkbox_id">Text</label>
    

    NOTE: ID must be unique on the page!

    Explanation

    Since the other answers don't mention it, a label can include up to 1 input and omit the for attribute, and it will be assumed that it is for the input within it.

    Excerpt from w3.org (with my emphasis):

    [The for attribute] explicitly associates the label being defined with another control. When present, the value of this attribute must be the same as the value of the id attribute of some other control in the same document. When absent, the label being defined is associated with the element's contents.

    To associate a label with another control implicitly, the control element must be within the contents of the LABEL element. In this case, the LABEL may only contain one control element. The label itself may be positioned before or after the associated control.

    Using this method has some advantages over for:

    • No need to assign an id to every checkbox (great!).

    • No need to use the extra attribute in the <label>.

    • The input's clickable area is also the label's clickable area, so there aren't two separate places to click that can control the checkbox - only one, no matter how far apart the <input> and actual label text are, and no matter what kind of CSS you apply to it.

    Demo with some CSS:

    label {
     border:1px solid #ccc;
     padding:10px;
     margin:0 0 10px;
     display:block; 
    }
    
    label:hover {
     background:#eee;
     cursor:pointer;
    }
    <label><input type="checkbox" />Option 1</label>
    <label><input type="checkbox" />Option 2</label>
    <label><input type="checkbox" />Option 3</label>

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(9条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度