Button inside a label

2019-04-20 03:15发布

I have a label with "for="the pointer to the checkbox input"" and as long as I know, this for can be added only for label. Therefore, I need to add inside of the label a <button>(I need it), but the click event isn't working properly - it doesn't check the checkbox the for is pointing to.

What are the possibilities I can use here if I must place <button> inside the label, with only html+css coding?

some code for example:

<input type="checkbox" id="thecheckbox" name="thecheckbox">
<div for="thecheckbox"><button type="button">Click Me</button></div>

4条回答
地球回转人心会变
2楼-- · 2019-04-20 03:46

You can use transparent pseudo element that overlays the checkbox and the button itself that will catch mouse events.

Here's an example:

html:

<label>
  <input type="checkbox">
  <button class="disable">button</button>
</label>

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;
}
查看更多
看我几分像从前
3楼-- · 2019-04-20 03:54

It turns out you can make a <button> operate an input, but only if you put the <label> inside the <button>.

<button type="button">
  <label for="my-checkbox">Button go outside the label</label>
</button>
<input type="checkbox" id="my-checkbox">

Although this contravenes the W3C specs:

The interactive element label must not appear as a descendant of the button element. https://www.w3.org/TR/html-markup/label.html

查看更多
成全新的幸福
4楼-- · 2019-04-20 03:54

HTML:

<label for="whatev"
       onclick="onClickHandler">
    <button>Imma button, I prevent things</button>
</label>

JS:

const onClickHandler = (e) => {
    if(e.target!==e.currentTarget) e.currentTarget.click()
}

Target is the click target, currentTarget is the label in this case.

Without the if statement the event is fired twice if clicked outside of the event preventing area.

Not cross browser tested.

查看更多
老娘就宠你
5楼-- · 2019-04-20 04:00

The best solution is to style is like a button.

If you're using a CSS framework, like bootstrap, you can give the label classes such as btn and btn-default. This will style it like a button. You may need to adjust the css property of the line-height manually like so:

label.btn {
    line-height: 1.75em;
}

Then, to get the on click styles as a button, add these styles:

input[type=radio]:checked ~ label.btn {
    background-color: #e6e6e6;
    border-color: #adadad;
    color: #333;
}

This will take the input that is checked and give the next label element in the dom that has the class btn, bootstrap btn-default button clicked styles. Adjust colors as fit.

查看更多
登录 后发表回答