問(wèn)題描述
我正在使用帶有數(shù)值的基本 HTML <input type="text"/>
文本字段.
I’m working with basic HTML <input type="text"/>
text field with a numeric value.
我正在添加 JavaScript 事件 keyup
以查看用戶何時(shí)按下向上箭頭鍵 (e.which == 38
) - 然后我增加數(shù)值.
I’m adding JavaScript event keyup
to see when user presses arrow up key (e.which == 38
) – then I increment the numeric value.
代碼運(yùn)行良好,但有一件事讓我很頭疼.當(dāng)我按向上箭頭鍵時(shí),Safari/Mac 和 Firefox/Mac 都會(huì)在最開(kāi)始移動(dòng)光標(biāo).據(jù)我所知,這是每個(gè) <input type="text"/>
文本字段的默認(rèn)行為,這是有道理的.
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.
但這不會(huì)產(chǎn)生光標(biāo)前后跳動(dòng)的非常美觀的效果(在更改值之后).
But this creates not a very aesthetic effect of cursor jumping back and forward (after value was altered).
一開(kāi)始的跳轉(zhuǎn)發(fā)生在 keydown
上,但即使有了這些知識(shí),我也無(wú)法阻止它發(fā)生.我嘗試了以下方法:
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
事件也無(wú)濟(jì)于事.
Putting e.preventDefault()
in keyup
event doesn’t help either.
有什么辦法可以防止光標(biāo)移動(dòng)嗎?
Is there any way to prevent cursor from moving?
推薦答案
要保留光標(biāo)位置,請(qǐng)?jiān)诟闹抵皞浞?input.selectionStart
.
To preserve cursor position, backup input.selectionStart
before changing value.
問(wèn)題在于 WebKit 對(duì) keydown
做出反應(yīng),而 Opera 更喜歡 keypress
,因此存在問(wèn)題:兩者都被處理和限制.
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);
這篇關(guān)于按向上箭頭時(shí)防止文本輸入中的默認(rèn)行為的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!