我有一个文本框有一个数值。现在我想要的是在按住任何箭头键的同时继续增加该数值。如果我只按一次,我知道该怎么做。它只会增加1。但是如果我想在按住箭头键的同时继续增加值怎么办。怎么做?
谢谢
我有一个文本框有一个数值。现在我想要的是在按住任何箭头键的同时继续增加该数值。如果我只按一次,我知道该怎么做。它只会增加1。但是如果我想在按住箭头键的同时继续增加值怎么办。怎么做?
谢谢
有一个小的 jQuery 插件可以做到这一点: https ://github.com/nakupanda/number-updown
用途:
$('#simplest').updown();
$('#step').updown({ step: 10, shiftStep: 100 });
$('#minMax').updown({ min: -10, max: 10 });
$('#minMaxCircle').updown({ min: -10, max: 10, circle: true });
在此处查看现场演示:http: //jsfiddle.net/XCtaH/embedded/result/
支持键盘和鼠标滚轮事件
我没有完全尝试和测试,但这里有一个想法 - 您可能想要跟踪 KeyDown 事件,因为这是第一次按下键时操作系统排队的事件。您可能还希望在以这种方式递增时实现某种延迟,以免压倒客户端脚本并使数字快速变化以供用户跟踪。
好的,经过一些测试,我在这里做了一些测试,它是如何完成的:
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";
}
如果您不关心支持 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;
}
我想这样做,我只是使用 type="number" 的输入字段