Disable scrolling on `<input type=number>`

后端 未结 15 1765
小蘑菇
小蘑菇 2020-12-02 07:13

Is it possible to disable the scroll wheel changing the number in an input number field? I\'ve messed with webkit-specific CSS to remove the spinner but I\'d like to get rid

相关标签:
15条回答
  • 2020-12-02 08:09

    If you want a solution that doesn’t need JavaScript, combining some HTML functionality with a CSS pseudo-element does the trick:

    span {
      position: relative;
      display: inline-block; /* Fit around contents */
    }
    
    span::after {
      content: "";
      position: absolute;
      top: 0; right: 0; bottom: 0; left: 0; /* Stretch over containing block */
      cursor: text; /* restore I-beam cursor */
    }
    
    /* Restore context menu while editing */
    input:focus {
      position: relative;
      z-index: 1;
    }
    <label>How many javascripts can u fit in u mouth?
      <span><input type="number" min="0" max="99" value="1"></span>
    </label>

    This works because clicking on the contents of a <label> that’s associated with a form field will focus the field. However, the “windowpane” of the pseudo-element over the field will block mousewheel events from reaching it.

    The drawback is that the up/down spinner buttons no longer work, but you said you had removed those anyway.


    In theory, one could restore the context menu without requiring the input to be focused first: :hover styles shouldn’t fire when the user scrolls, since browsers avoid recalculating them during scrolling for performance reasons, but I haven’t thoroughly cross-browser/device tested it.

    0 讨论(0)
  • 2020-12-02 08:11

    I have an alternative suggestion. The problem I see with most of the common recommendation of firing a blur event is that it has unexpected side-effects. It's not always a good thing to remove a focus state unexpectedly.

    Why not this instead?

    <input type="number" onwheel="return false;" />

    It's very simple and straight-forward, easy to implement, and no side-effects that I can think of.

    0 讨论(0)
  • 2020-12-02 08:13

    Typescript Variation

    Typescript needs to know that you're working with an HTMLElement for type safety, else you'll see lots of Property 'type' does not exist on type 'Element' type of errors.

    document.addEventListener("mousewheel", function(event){
      let numberInput = (<HTMLInputElement>document.activeElement);
      if (numberInput.type === "number") {
        numberInput.blur();
      }
    });
    
    0 讨论(0)
提交回复
热议问题