Button inside a label

后端 未结 5 1044
后悔当初
后悔当初 2021-02-12 15:20

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

相关标签:
5条回答
  • 2021-02-12 15:35

    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.

    0 讨论(0)
  • 2021-02-12 15:37

    What I've done is the following:

    <label htmlFor="fileUpload">
      <button onclick="onButtonClick">upload</button>
    </label>
    <input id="fileUpload" type="file" style="display: none"/>
    
    onButtonClick() {
      document.getElementById('fileUpload').click();
    }
    
    0 讨论(0)
  • 2021-02-12 15:43

    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

    0 讨论(0)
  • 2021-02-12 15:43

    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.

    0 讨论(0)
  • 2021-02-12 15:51

    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;
    }
    
    0 讨论(0)
提交回复
热议问题