禁止在 `<input type=number>` 上滚动 [英] Disable scrolling on `&lt;input type=number&gt;`

查看:56
本文介绍了禁止在 `<input type=number>` 上滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以禁用滚轮更改输入数字字段中的数字?我已经弄乱了特定于 webkit 的 CSS 来删除微调器,但我想完全摆脱这种行为.我喜欢使用 type=number 因为它在 iOS 上带来了一个不错的键盘.

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 of this behavior altogether. I like using type=number since it brings up a nice keyboard on iOS.

推荐答案

防止鼠标滚轮事件在其他人建议的 input-number 元素上的默认行为(调用blur()"通常不是首选方式它,因为那不会是用户想要的).

Prevent the default behavior of the mousewheel event on input-number elements like suggested by others (calling "blur()" would normally not be the preferred way to do it, because that wouldn't be, what the user wants).

但是.我会避免一直监听所有 input-number 元素上的 mousewheel 事件,并且仅在元素处于焦点时(即存在问题时)才这样做.否则,当鼠标指针位于 input-number 元素上的任何位置时,用户无法滚动页面.

BUT. I would avoid listening for the mousewheel event on all input-number elements all the time and only do it, when the element is in focus (that's when the problem exists). Otherwise the user cannot scroll the page when the mouse pointer is anywhere over a input-number element.

jQuery 的解决方案:

Solution for jQuery:

// disable mousewheel on a input number field when in focus
// (to prevent Cromium browsers change the value when scrolling)
$('form').on('focus', 'input[type=number]', function (e) {
  $(this).on('wheel.disableScroll', function (e) {
    e.preventDefault()
  })
})
$('form').on('blur', 'input[type=number]', function (e) {
  $(this).off('wheel.disableScroll')
})

(将焦点事件委托给周围的表单元素 - 以避免许多事件侦听器,这对性能不利.)

(Delegate focus events to the surrounding form element - to avoid to many event listeners, which are bad for performance.)

这篇关于禁止在 `<input type=number>` 上滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆