nik*_*tta 15 html css button css3 radio-button
我有一个label" for="the pointer to the checkbox input"",只要我知道,这for只能添加label.因此,我需要在labela <button>(我需要它)内部添加,但click事件无法正常工作 - 它不会检查for指向的复选框.
什么是我可以用在这里,如果我必须把可能性<button>里面label,只用HTML + CSS编码?
一些代码例如:
<input type="checkbox" id="thecheckbox" name="thecheckbox">
<div for="thecheckbox"><button type="button">Click Me</button></div>
Run Code Online (Sandbox Code Playgroud)
Sin*_*eta 11
事实证明,你可以做一个<button>操作的输入,但只有当你把<label> 里面的<button>.
<button type="button">
<label for="my-checkbox">Button go outside the label</label>
</button>
<input type="checkbox" id="my-checkbox">Run Code Online (Sandbox Code Playgroud)
虽然这违反了W3C规范:
交互式元素标签不得显示为按钮元素的后代. https://www.w3.org/TR/html-markup/label.html
小智 7
您可以使用覆盖复选框和按钮本身的透明伪元素来捕获鼠标事件。
下面是一个例子:
html:
<label>
<input type="checkbox">
<button class="disable">button</button>
</label>
Run Code Online (Sandbox Code Playgroud)
css:
.disable{pointer-events:fill}
label{position:relative}
label:after{
position: absolute;
content: "";
width: 100%;
height: 100%;
background: transparent;
top:0;
left:0;
right:0;
bottom:0;
}
Run Code Online (Sandbox Code Playgroud)
HTML:
<label for="whatev"
onclick="onClickHandler">
<button>Imma button, I prevent things</button>
</label>
Run Code Online (Sandbox Code Playgroud)
JS:
const onClickHandler = (e) => {
if(e.target!==e.currentTarget) e.currentTarget.click()
}
Run Code Online (Sandbox Code Playgroud)
Target 是点击目标,currentTarget 在这种情况下是标签。
如果没有 if 语句,如果在事件阻止区域外单击,则事件将触发两次。
未经过跨浏览器测试。
你可以这样做:
<label>
<button></button>
</label>
Run Code Online (Sandbox Code Playgroud)
CSS
label {
cursor: pointer; // not necessary but probably a good idea.
display: block; // depending on your structure.
}
button {
pointer-events: none;
}
Run Code Online (Sandbox Code Playgroud)
该display: block标签将只需要这样标签的边框完全包裹它的孩子(在这种情况下按钮)。