简体   繁体   English

在javascript中使用鼠标滚轮事件验证输入字段的问题

[英]Issue with Validating a Input Field with Mouse wheel event in javascript

I am trying to validate a Number Input field in Javascript. 我正在尝试在Javascript中验证数字输入字段。

Issue is, when I use mouse wheel to change the value I am unable to validate it correctly. 问题是,当我使用鼠标滚轮更改值时,我无法正确验证它。

If current value is 5, and i do a scroll up with mouse wheels, current value is being displayed as 5, not as 6. It seems the mouse event is being triggered at the start of the event. 如果当前值为5,并且我使用鼠标滚轮向上滚动,则当前值显示为5,而不显示为6.似乎在事件开始时触发了鼠标事件。 Hence it still has the old value. 因此它仍然具有旧的价值。

<label>Choose an ice cream flavor:
    <input type="number">
    <p></p>
</label>
<script>
var inputc = document.querySelector('input');
var pc = document.querySelector('p');
inputc.addEventListener('wheel', function (e){
  pc.innerText = 'The value is ' + inputc.value;
});
</script>

Link to jsfiddle: https://jsfiddle.net/3o8g7cdy/1/ 链接到jsfiddle: https ://jsfiddle.net/3o8g7cdy/1/

Any Idea on how to validate for this correclty. 关于如何验证此相关性的任何想法。 Thanks. 谢谢。

You can listen for input event instead of wheel . 您可以监听input事件而不是wheel

 var inputc = document.querySelector('input'); var pc = document.querySelector('p'); inputc.addEventListener('input', function (e){ pc.innerText = 'The value is ' + inputc.value; }); 
 <label>Choose an ice cream flavor: <input type="number"> <p></p> </label> 

Additional Information: If you still want to use wheel event, you may add some delay to value changing operation. 附加信息:如果您仍想使用滚轮事件,则可能会为更改值操作添加一些延迟。 Even setTimeout(function(){}, 0) will solve problem. 甚至setTimeout(function(){},0)也会解决问题。 How? 怎么样?

<label>Choose an ice cream flavor:
    <input type="number">
    <p></p>
</label>
<script>
var inputc = document.querySelector('input');
var pc = document.querySelector('p');
inputc.addEventListener('wheel', function (e){
 setTimeout(function(){ pc.innerText = 'The value is ' + inputc.value;},0);
});
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM