当我用javascript按键盘上的箭头键时增加数字

时间:2010-10-06 23:58:23

标签: javascript increment arrow-keys

我有一个文本框有一个数值。 现在我想要的是在按住任意箭头键时继续增加该数值。 如果我只按一次,我知道怎么做。它只会增加1。但是,如果我想在按住箭头键的同时继续增加值。怎么做?

感谢

4 个答案:

答案 0 :(得分:2)

有一个小的jQuery插件用于执行此操作: https://github.com/nakupanda/number-updown

用途:

$('#simplest').updown();

$( '#步骤')。UPDOWN({     步骤:10,     shiftStep:100 });

$( '#MINMAX')。UPDOWN({     min:-10,     最大值:10 });

$( '#minMaxCircle')。UPDOWN({     min:-10,     最大值:10,     圈子:是的 });

在此处观看现场演示: http://jsfiddle.net/XCtaH/embedded/result/

键盘和鼠标滚轮事件支持

答案 1 :(得分:1)

我没有对此进行过全面的尝试和测试,但这是一个想法 - 您可能想要跟踪KeyDown事件,因为这是在首次按下该键时操作系统排队的事件。您可能还希望在以此方式递增时实现某种延迟,以免压倒客户端脚本并使数字以高速更改为高以供用户跟踪。

答案 2 :(得分:0)

如果您不关心支持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 Quirks中进行了测试:

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;
}

答案 3 :(得分:0)

好的,我在这里做的一些测试是如何完成的:

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"; 
}