![](/img/trans.png)
[英]Cross-browser way to get automatically repeating keydown events when key is held down
[英]HTML Canvas: Controlling keydown registry when key is held down
我正在寻找一种方法来控制在按下键的情况下在给定的时间段内注册了多少键按下事件。 我有两个动画函数collapse()
和expand()
,当按下向下键时,它们可以折叠并展开一个框。 我已将其固定,以使第二个动画在第一个动画之后开始。 但是,我有一个计时器,在第一个动画中设置了hovering(t)
,每次按下该键时都会重置该动画,以使第二个动画直到按键被释放且计时器到期后才开始。
function collapse(){
if(h > 1 && arrayCount < myArray.length){
reqAnimFrame(collapse);
h -= 10;
clear();
draw();
} else {
arrayCount += 1;
h = 0;
clearHoverTimer();
hovering(250);
}
}
function expand(){
if(h < 100){
reqAnimFrame(expand);
h += 10;
clear();
draw();
} else {
h = 100;
clear();
draw();
}
}
这是我的问题所在:第一个动画函数还通过arrayCount变量在字符串数组中循环。 当崩溃()触发时,arrayCount会增加1。 不幸的是,当按下键时,它会快速连续触发折叠功能,并且阵列循环过快。
是否可以限制按键事件的时间,以便说一半的按键被注册?
我尝试将变量heldDown
设置为false
,这将允许keyEvent注册。 keyEvent将调用collapse
并启动heldDownTimer
。 一旦heldDownTimer
过期, heldDown
将被重置为false
并且循环将重新开始。
设置标志,指示折叠和展开动画的当前状态。
var doCollapsing
指示折叠代码是否应设置动画。
var doExpanding
指示扩展代码是否应设置动画。
在keydown处理程序中,仅当标志指示动画循环处于空闲状态时,才设置标志,可以忽略“额外” keydown。
// listen for keydown and doCollapsing only if the animation is currently idle
if(!doCollapsing && !doExpanding){
doCollapsing=true; // start collapsing
doExpanding=false; // don't expand until a keyup fires
}
这将导致折叠+展开执行一次,而不是每次按下键都会被触发。
// variables indicating the state of the animation
var doCollapsing=false;
var doExpanding=false;
// listen for keydown events
document.addEventListener("keydown",handleKeydown,false);
// listen for keyup events
document.addEventListener("keyup",handleKeyup,false);
// start the animation loop
requestAnimationFrame(animate);
// handle keydown events
function handleKeydown(e){
// listen for keydown
// doCollapsing only if the animation is idle
if(!doCollapsing && !doExpanding){
doCollapsing=true;
doExpanding=false;
}
}
// handle keyup events
function handleKeyup(e){
doExpanding=true;
}
// the animation loop
function animate(time){
requestAnimationFrame(animate);
if(doCollapsing){
// Do collapsing until done
// When done: doCollapsing=false;
}else if(doExpanding && hoveringTimerHasExpired){
// Do expanding until done
// When done: doExpanding=false;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.