Javascript 在jquery中每秒点击事件触发X次
我正在尝试为我在jquery帮助下编写的一个小游戏制作触摸控制。但我就是想不出如何编写一个函数,它基本上做的事情与按下一个键时发生的事情相同。 你能帮帮我吗 附:这不是我的原始代码Javascript 在jquery中每秒点击事件触发X次,javascript,jquery,Javascript,Jquery,我正在尝试为我在jquery帮助下编写的一个小游戏制作触摸控制。但我就是想不出如何编写一个函数,它基本上做的事情与按下一个键时发生的事情相同。 你能帮帮我吗 附:这不是我的原始代码 问题是,你想多久检查一次用户输入的变化。在JS中,对于计时器的分辨率,您是非常有限的。尽管如此,请注意,所有事件都是按顺序运行的,因此事件排队并可能汇总。对于setInterval()来说尤其如此,因为它严格地对新事件排队,即使之前触发的事件尚未处理 类似这样的工作原理: var pressed; // flag
问题是,你想多久检查一次用户输入的变化。在JS中,对于计时器的分辨率,您是非常有限的。尽管如此,请注意,所有事件都是按顺序运行的,因此事件排队并可能汇总。对于setInterval()来说尤其如此,因为它严格地对新事件排队,即使之前触发的事件尚未处理 类似这样的工作原理:
var pressed; // flag for continous press between mousedown and timer-events
var duration; // number of times the timer fired for a continous mousedown
var timeout; // reference to timer-event used to reset the timer on mouseup
$(document).mousedown = function(){
pressed = true;
handleMousedown(false);
}
function handleMousedown(continued){
if(pressed){ // if still pressed
if(continued){ // and fired by the timer
duration++;
// measure time, use duration
// do anything
}
timeout = setTimeout('handleMousedown(true)', 100); // wait for another 100ms then repeat
}
}
$(document).mouseup = function() {
// do sth on mouseup
pressed = false; // reset flag for continous mousedown
clearTimeout(timeout); // abandon the timer
}
$(document).mouseout = function() { // $(document).mouseenter = function(){
// do sth on mouse leave or mouse entering again according to how your game should behave
pressed = false; // reset flag for continous mousedown
clearTimeout(timeout); // abandon the timer
}
请添加您正在处理的代码。提问前请阅读。你能不能用
keydown
和keydup
代替mousedown
和mouseup
?@MattBurland的问题是触摸设备通常没有键盘。或者我能让一个按钮像钥匙一样吗?@RachelGallen我想超时不是问题。我可能没有正确地解释我的问题。。我基本上只希望这个代码适用于触摸屏
var pressed; // flag for continous press between mousedown and timer-events
var duration; // number of times the timer fired for a continous mousedown
var timeout; // reference to timer-event used to reset the timer on mouseup
$(document).mousedown = function(){
pressed = true;
handleMousedown(false);
}
function handleMousedown(continued){
if(pressed){ // if still pressed
if(continued){ // and fired by the timer
duration++;
// measure time, use duration
// do anything
}
timeout = setTimeout('handleMousedown(true)', 100); // wait for another 100ms then repeat
}
}
$(document).mouseup = function() {
// do sth on mouseup
pressed = false; // reset flag for continous mousedown
clearTimeout(timeout); // abandon the timer
}
$(document).mouseout = function() { // $(document).mouseenter = function(){
// do sth on mouse leave or mouse entering again according to how your game should behave
pressed = false; // reset flag for continous mousedown
clearTimeout(timeout); // abandon the timer
}