防止箭头键更改数字输入中的值 [英] Prevent arrow keys from changing values in a number input

查看:75
本文介绍了防止箭头键更改数字输入中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在与此类似的网页上有一个输入控件:

I have an input control on a webpage similar to this:

<input type="number" name="value" />

如果此控件具有焦点,并且我按下了向上或向下箭头键,则文本框中的值将递增或递减(IE中除外).我想禁用此功能,最好使用CSS.我已经使用CSS删除了微调按钮.我意识到我可以使用JavaScript来捕获keydown事件,但是我想允许箭头键继续向上或向下滚动页面.

If this control has focus and I hit either the up or down arrow keys, then the value in the textbox increments or decrements (except in IE). I would like to disable this feature, preferably using CSS. I already have the spinner buttons removed using CSS. I realize I could use JavaScript to capture the keydown event, but I want to allow the arrow keys to continue to scroll the page up or down.

推荐答案

由于CSS处理显示,并且我们在此处讨论行为和键盘事件,因此无法完全使用CSS来描述您所描述的行为.

There is no way of doing the behavior you are describing purely with CSS because CSS handles display and we are talking about behavior and keyboard events here.

我建议向您的输入添加一个事件侦听器,这将防止箭头键对其产生影响,而实际上阻止了带有输入的页面滚动不清晰:

I would suggest to add an event listener to your input which will prevent the arrow keys from having an effect on it witout actually preventing the page scroll with the input is not in focus:

document.getElementById('yourInputID').addEventListener('keydown', function(e) {
    if (e.which === 38 || e.which === 40) {
        e.preventDefault();
    }
});

如果输入是焦点,如果您希望箭头键滚动页面事件,我建议使用JQuery,它将使您编写的代码更少,并且将支持所有浏览器.

If by any chance you want the arrow keys to scroll the page event if the input is in focus, I would suggest using JQuery which will allow you to write less code and it will support all browsers.

这篇关于防止箭头键更改数字输入中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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