当我按UIView
时,我想创建两个计数器我想 counter1 开始计数,当我按downKey
时我想停止第一个计数器并开始 counter2 ....我知道我需要使用keyLeft
函数,但我不知道我需要在哪里使用它,这里是JSFiddle
看看我的意思
HTML:
clearInterval()
JS:
<div id="left"></div>
<div id="down"></div>
答案 0 :(得分:4)
你需要在keydown之外声明down_move和right_move:
var right_move, down_move;
$('body').keydown(function (e) {
switch (e.which) {
case 39:
clearInterval(down_move);
var i=0;
right_move = setInterval(function(){
$('#left').html(i);
i++
}, 1000)
break;
case 40:
clearInterval(right_move);
var j = 0;
down_move = setInterval(function(){
$('#down').html(j)
j++;
}, 1000);
break;
default:
}
e.preventDefault();
});
答案 1 :(得分:0)
这似乎是一个范围问题,这是我如何做到的: updated fiddle
var Interval = function(intervalFunc, selector){
var interval;
this.start = function(){
interval = setInterval(intervalFunc, 1000);
},
this.stop = function(){
clearInterval(interval);
}
}
var i = 0;
var rightBtnInterval = new Interval(function downInterval(){
$('#right').html(i)
i++;
});
var j = 0;
var downBtnInterval = new Interval(function downInterval(){
$('#down').html(j)
j++;
});
$('body').keydown(function (e) {
switch (e.which) {
case 39:
rightBtnInterval.stop();
downBtnInterval.start();
break;
case 40:
downBtnInterval.stop();
rightBtnInterval.start();
break;
default:
}
e.preventDefault();
});
答案 2 :(得分:0)
您必须在功能之外存储停止的间隔
警告左侧的ascii代码为37.
这是JSFiddle看到我的更改:
var storeInterval = null;
$('body').keydown(function (e) {
switch (e.which) {
case 37:
clearInterval(storeInterval);
var i=0;
storeInterval = setInterval(function(){
$('#left').html(i);
i++
}, 1000)
break;
case 40:
clearInterval(storeInterval);
var j = 0;
storeInterval = setInterval(function(){
$('#down').html(j)
j++;
}, 1000);
break;
default:
}
e.preventDefault();
});
&#13;
<div id="left"></div>
<div id="down"></div>
&#13;