首页 > 解决方案 > 自定义复选框 - 通过单击标签停止复选框的能力

问题描述

我有一个复选框。它看起来像这样。

在此处输入图像描述

它工作正常...除了您可以通过单击标签来选中该框。这是有问题的,原因有两个:

  1. 我不喜欢
  2. 我需要用户能够单击蓝色链接。现在,它只是选中该框

这是我当前的 HTML:

 <label className="container">I have read and do accept <a href={props.link}>{props.topic}</a>
    <input type="checkbox" onChange={event => props.onChange(event)}/>
    <span className="checkmark"></span>
 </label>

这是我的 css,它(大致)来自这里:https ://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_custom_checkbox

/* Hide the browser's default checkbox */
.container input {
    position: absolute;
    opacity: 0;
    cursor: pointer;
}

/* Create a custom checkbox */
.checkmark {
    position: absolute;
    top: -2px;
    left: 0;
    height: 21px;
    width: 21px;
    background-color: #eee;
}

/* On mouse-over, add a grey background color */
.container:hover input ~ .checkmark {
    background-color: #ccc;
}

/* When the checkbox is checked, add a blue background */
.container input:checked ~ .checkmark {
    background-color: rgb(29, 29, 29);
}

/* Create the checkmark/indicator (hidden when not checked) */
.checkmark:after {
    content: "";
    position: absolute;
    display: none;
}

/* Show the checkmark when checked */
.container input:checked ~ .checkmark:after {
    display: block;
}

/* Style the checkmark/indicator */
.container .checkmark:after {
    left: 8px;
    top: 4px;
    width: 4px;
    height: 9px;
    border: solid white;
    border-width: 0 2px 2px 0;
    -webkit-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    transform: rotate(45deg);
}

有什么想法吗?您实际上可以在我提供的 W3C 笔中使用它。

标签: htmlcss

解决方案


首先,您可以将复选框拉入它自己的容器中,然后,如果您希望标签在语义上与该特定输入相关,则必须为其分配一个属性,并为输入字段for分配一个相应的属性。id现在,您拥有两全其美的优势。链接是可点击的,而标签的其余部分选中复选框。

<div class="checkbox-container">
  <input type="checkbox" id="checkbox">
  <span className="checkmark"></span>
</div>
<label class="container" for="checkbox">
  I have read and do accept the <a href="#">terms and conditions</a>
</label>

看起来您已经弄清楚了自定义复选框 UI 部分,所以我将把它留给您。


推荐阅读