html - 自定义复选框 - 通过单击标签停止复选框的能力
问题描述
我有一个复选框。它看起来像这样。
它工作正常...除了您可以通过单击标签来选中该框。这是有问题的,原因有两个:
- 我不喜欢
- 我需要用户能够单击蓝色链接。现在,它只是选中该框
这是我当前的 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 笔中使用它。
解决方案
首先,您可以将复选框拉入它自己的容器中,然后,如果您希望标签在语义上与该特定输入相关,则必须为其分配一个属性,并为输入字段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 部分,所以我将把它留给您。
推荐阅读
- filter - 是否可以仅保留对公共 Google 表格客户端的更改?
- css - 当左侧有很多内容时,防止 CSS 将节点包裹在其最大宽度以下的树中,例如思维导图
- unity3d - 如何使对象的参考框架位于其尖端而不是其中心(Unity3d)?
- postman - 在邮递员收集运行中禁用请求
- batch-file - 批处理文件可以做到这一点吗?
- python - Plotly:python上的两个x轴(相同的y轴)
- android - 我已经在 react native 中构建了我的应用程序,但我想减小大小
- java - 在嵌套枚举实现接口中继承泛型类型
- python - 如何将包含 4916 张图片(375x375x3)的 mat 文件转换为 numpy 数组?
- python - 在 __iter__ 中使用