我有一个文本框有一个数值。 现在我想要的是在按住任何方向键的同时不断增加数字值。 我知道如何做到这一点,如果我只按一次。它只会增加1。但是如果我想在持有箭头键的同时继续增加价值。怎么做?当我按下键盘上的箭头键时增加数字
感谢
我有一个文本框有一个数值。 现在我想要的是在按住任何方向键的同时不断增加数字值。 我知道如何做到这一点,如果我只按一次。它只会增加1。但是如果我想在持有箭头键的同时继续增加价值。怎么做?当我按下键盘上的箭头键时增加数字
感谢
这是不完全试图通过我测试,但这里是一个思想 - 你可能需要跟踪的KeyDown事件,因为这是它是由OS排队时,第一次按下该键的事件。当你这样增加时,你可能也想实现某种延迟,以免压倒客户端脚本,并且数字的变化速度很快,以便用户跟踪。
如果你不关心支持歌剧,这是很容易:
textbox.onkeydown = function(e)
{
if (e.keyCode == 38)
{
incrementTextBox();
}
}
但是,Opera不关键重复火......你必须通过调用incrementTextBox()
在以模仿间隔,当钥匙被抬起时停止。我测试了WebKit中器(Chrome 6.0),FF3,歌剧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;
}
即使在我抬起箭头键后,这个值仍然会增加值。 – SolidSnake 2010-10-07 02:14:27
这就是我得到的结果,因为我没有测试自己的答案。但是,它在Opera中起作用! :)我会修改我的答案。 – gilly3 2010-10-08 18:10:55
确定一些测试中,我在这里作出后是它如何做的:
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";
}
有一个小的jQuery插件,这样做的: https://github.com/nakupanda/number-updown
用途:
$('#simplest').updown();
$('#step')。updown({ step:10, shiftStep:100 });
$('#minMax')。updown({min:-10, max:10 }); 。
$( '#minMaxCircle')可逆({ 分钟:-10, 最大:10, 圆:真 });
查看现场演示这里: http://jsfiddle.net/XCtaH/embedded/result/
键盘和鼠标滚轮事件supporte
'onkeydown'确实会工作,也不会是“压倒性的”快速在任何情况下 - 键只会重复在在OS设置中设置的速率。 – casablanca 2010-10-07 00:18:52
好吧,那么好! – Jas 2010-10-07 00:24:02