Disable scrolling on `<input type=number>`

后端 未结 15 1818
小蘑菇
小蘑菇 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 07:52

    While trying to solve this for myself, I noticed that it's actually possible to retain the scrolling of the page and focus of the input while disabling number changes by attempting to re-fire the caught event on the parent element of the on which it was caught, simply like this:

    e.target.parentElement.dispatchEvent(e);
    

    However, this causes an error in browser console, and is probably not guaranteed to work everywhere (I only tested on Firefox), since it is intentionally invalid code.

    Another solution which works nicely at least on Firefox and Chromium is to temporarily make the element readOnly, like this:

    function handleScroll(e) {
      if (e.target.tagName.toLowerCase() === 'input'
        && (e.target.type === 'number')
        && (e.target === document.activeElement)
        && !e.target.readOnly
      ) {
          e.target.readOnly = true;
          setTimeout(function(el){ el.readOnly = false; }, 0, e.target);
      }
    }
    document.addEventListener('wheel', function(e){ handleScroll(e); });
    

    One side effect that I've noticed is that it may cause the field to flicker for a split-second if you have different styling for readOnly fields, but for my case at least, this doesn't seem to be an issue.

    Similarly, (as explained in James' answer) instead of modifying the readOnly property, you can blur() the field and then focus() it back, but again, depending on styles in use, some flickering might occur.

    Alternatively, as mentioned in other comments here, you can just call preventDefault() on the event instead. Assuming that you only handle wheel events on number inputs which are in focus and under the mouse cursor (that's what the three conditions above signify), negative impact on user experience would be close to none.

提交回复
热议问题