用javascript按键盘上的箭头键时增加数字
我有一个文本框,它有一个数值。 现在我想要的是在按住任意箭头键的同时不断增加数值。 如果我只按了一次,我知道怎么做。它将只增加1。但是如果我想在按住箭头键的同时不断增加值,该怎么办。怎么做用javascript按键盘上的箭头键时增加数字,javascript,increment,arrow-keys,Javascript,Increment,Arrow Keys,我有一个文本框,它有一个数值。 现在我想要的是在按住任意箭头键的同时不断增加数值。 如果我只按了一次,我知道怎么做。它将只增加1。但是如果我想在按住箭头键的同时不断增加值,该怎么办。怎么做 谢谢我还没有完全尝试和测试过这一点,但我有一个想法-您可能希望跟踪按键事件,因为这是操作系统在首次按下按键时排队等待的事件。当以这种方式递增时,您可能还希望实现某种延迟,以避免淹没客户端脚本,并使数字以很高的速度更改,以便用户跟踪。如果您不关心支持Opera,这很容易: textbox.onkeydown =
谢谢我还没有完全尝试和测试过这一点,但我有一个想法-您可能希望跟踪按键事件,因为这是操作系统在首次按下按键时排队等待的事件。当以这种方式递增时,您可能还希望实现某种延迟,以避免淹没客户端脚本,并使数字以很高的速度更改,以便用户跟踪。如果您不关心支持Opera,这很容易:
textbox.onkeydown = function(e)
{
if (e.keyCode == 38)
{
incrementTextBox();
}
}
然而,Opera不会为按键重复触发keydown
。。。您必须通过每隔一段时间调用incrementTextBox()
,并在拔出钥匙时停止来模拟这一点。我在WebKit(Chrome 6.0)、FF3、Opera 10.6、IE7、IE8、IE9甚至IE怪癖中对此进行了测试:
var textbox = null;
window.onload = function()
{
var timeoutId = null;
var intervalId = null;
var incrementRepeatStarted = false;
function startIncrementKeyRepeat()
{
timeoutId = window.setTimeout(function()
{
intervalId = window.setInterval(incrementTextBox, 50);
}, 300);
}
function abortIncrementKeyRepeat()
{
window.clearTimeout(timeoutId);
window.clearInterval(intervalId);
timeoutId = null;
intervalId = null;
}
function endIncrementKeyRepeat()
{
abortIncrementKeyRepeat();
incrementRepeatStarted = false;
}
textbox = document.getElementById("incrementer");
textbox.onkeydown = function(e)
{
e = e || window.event;
if (e.keyCode == 38)
{
if (!incrementRepeatStarted)
{
startIncrementKeyRepeat();
incrementRepeatStarted = true;
}
else if (timeoutId || intervalId)
{
abortIncrementKeyRepeat();
}
incrementTextBox();
}
else if (incrementRepeatStarted)
{
endIncrementKeyRepeat();
}
}
textbox.onkeyup = endIncrementKeyRepeat;
}
function incrementTextBox()
{
var val = parseInt(textbox.value) || 0;
val++;
textbox.value = val;
}
好的,在我做了一些测试之后,这里是如何完成的:
var setTimeoutId;
var keyIs = "up";
function myIncrementFunction()
{
var num = parseFloat(myText.value)+1;
myText.value = num;
}
myText.onkeydown = function(e)
{
keyIs = "down";
if(keyIs == "down")
{
var e = e || event ;
if (e.keyCode == 38)
{
for(var s=0; s<1; s++)
setTimeoutId = setTimeout('myIncrementFunction()',100);
}
}
}
myText.onkeyup = function(e)
{
keyIs = "up";
}
var setTimeoutId;
var keyIs=“向上”;
函数myIncrementFunction()
{
var num=parseFloat(myText.value)+1;
myText.value=num;
}
myText.onkeydown=函数(e)
{
keyIs=“向下”;
如果(keyIs==“向下”)
{
var e=e | |事件;
如果(e.keyCode==38)
{
对于(var s=0;s,有一个小的jQuery插件用于执行此操作:
用途:
$('#simplest').updown();
$(“#步”)。向上向下({
步骤:10,
班次:100
}))
$('#minMax')。向上向下({
最小:-10,
最多:10
}))
$('minMaxCircle')。向上向下({
最小:-10,
最高:10,
圆圈:对
}))
在此处查看实时演示:
键盘和鼠标滚轮事件支持onkeydown
确实可以工作,而且它在任何情况下都不会“压倒性地”快速-按键只会以操作系统设置中设置的速率重复。这就是我没有测试自己答案的原因。但是,它在Opera中工作!:)我会修改我的答案。