在向上箭头的同时,防止文本输入中的默认行为 [英] Prevent default behavior in text input while pressing arrow up
问题描述
我正在使用带有数值的基本HTML < input type =text/>
文本字段。
I’m working with basic HTML <input type="text"/>
text field with a numeric value.
我正在添加JavaScript事件 keyup
以查看用户是否按下向上键( e.which == 38
) - 然后我增加数值。
I’m adding JavaScript event keyup
to see when user presses arrow up key (e.which == 38
) – then I increment the numeric value.
代码运行良好,但有一件事情会让我失望。当我按向上箭头键时,Safari / Mac和Firefox / Mac都会在开始时移动光标。据我所知,这是每个< input type =text/>
文本字段的默认行为。
The code works well, but there’s one thing that bugs me. Both Safari/Mac and Firefox/Mac move cursor at the very beginning when I’m pressing the arrow up key. This is a default behavior for every <input type="text"/>
text field as far as I know and it makes sense.
但是,这不会导致光标跳转和转发(在值被更改后)的非常美观的效果。
But this creates not a very aesthetic effect of cursor jumping back and forward (after value was altered).
开始时的跳转发生在 keydown
上,但即使有这个知识,我无法防止它发生。我尝试了以下内容:
The jump at the beginning happens on keydown
but even with this knowledge I’m not able to prevent it from occuring. I tried the following:
input.addEventListener('keydown', function(e) {
e.preventDefault();
}, false);
将 e.preventDefault()
code> keyup 事件也没有帮助。
Putting e.preventDefault()
in keyup
event doesn’t help either.
有没有办法阻止光标移动?
Is there any way to prevent cursor from moving?
推荐答案
要保留光标位置,请在更改值之前备份 input.selectionStart
。
To preserve cursor position, backup input.selectionStart
before changing value.
问题是WebKit对 keydown
和Opera喜欢 keypress
所以有kludge:都被处理和调节。
The problem is that WebKit reacts to keydown
and Opera prefers keypress
, so there's kludge: both are handled and throttled.
var ignoreKey = false;
var handler = function(e)
{
if (ignoreKey)
{
e.preventDefault();
return;
}
if (e.keyCode == 38 || e.keyCode == 40)
{
var pos = this.selectionStart;
this.value = (e.keyCode == 38?1:-1)+parseInt(this.value,10);
this.selectionStart = pos; this.selectionEnd = pos;
ignoreKey = true; setTimeout(function(){ignoreKey=false},1);
e.preventDefault();
}
};
input.addEventListener('keydown',handler,false);
input.addEventListener('keypress',handler,false);
这篇关于在向上箭头的同时,防止文本输入中的默认行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!