按向上箭头时防止文本输入中的默认行为
我正在使用带有数值的基本 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()
放入 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
,因此存在问题:两者都被处理和限制.
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);
相关文章