数字输入滚动的 HTML5 事件监听器 - 仅限 Chrome

2022-01-15 00:00:00 google-chrome event-handling jquery html

我正在玩一些 HTML5 元素,并遇到了一个有趣的行为.这仅适用于 Chrome.

I'm playing around with some HTML5 elements, and ran into a fun behavior. This only works in Chrome.

使用数字输入类型,您可以设置最小值、最大值和步长,并通过上下箭头来控制输入.<input type="number" min="0" max="100" step="5"/>

Using an input type of number, you can set the min, max, and step, and get up and down arrows to control the input. <input type="number" min="0" max="100" step="5" />

我发现绑定单击事件侦听器会捕获箭头上的按下,因为在字段模糊之前不会真正发生更改.您还可以使用键盘上的向上和向下箭头键在限制范围内更改值,并且按键绑定可以获取这些值.

I've found that binding a click event listener captures presses on the arrows, as a change won't actually occur until the field is blurred. You can also use the up and down arrow keys on your keyboard to change the value within the limits, and a keypress bind can pick these up.

但是,在 Chrome 中,您也可以使用鼠标滚轮来更改输入,方法是将鼠标悬停在输入上并滚动.但是,我一直无法找到监听此事件的方法.

In Chrome, however, you can also use your mouse wheel to change the input, by hovering over the input and scrolling. I have not been able to find a way to listen for this event, however.

jsfiddle 示例

HTML:

<input type="number" min="0" max="100" step="5" id="test" />

JavaScript(使用 jQuery):

JavaScript (using jQuery):

$( '#test' ).click(function(){
   $( this ).after( '<br />click' ); 
});

$( '#test' ).change(function(){
   $( this ).after( '<br />change' ); 
});

$( '#test' ).keypress(function(){
   $( this ).after( '<br />keypress' ); 
});

关于如何监听滚动变化的任何想法?同样,在撰写本文时,这仅适用于 Chrome.

Any ideas on how to listen for that scroll change? Again, this only works in Chrome as of this writing.

推荐答案

jQuery 鼠标滚轮插件似乎可以解决问题.http://plugins.jquery.com/project/mousewheel

The jQuery Mouse Wheel plugin seems to do the trick. http://plugins.jquery.com/project/mousewheel

$( '#test' ).mousewheel(function(){
   $( this ).after( '<br />mouse wheel' ); 
});

相关文章