0

我正在尝试为我在 jquery 的帮助下编写的一个小游戏制作触摸控件。但我只是不知道如何编写一个函数,该函数基本上与您按住某个键时发生的事情相同。请你帮助我好吗?

PS。它不是我的代码

jQuery.fn.mousehold = function(timeout, f) {
    if (timeout && typeof timeout == 'function') {
        f = timeout;
        timeout = 100;
    }
    if (f && typeof f == 'function') {
        var timer = 0;
        var fireStep = 0;
        return this.each(function() {
            jQuery(this).mousedown(function() {
                fireStep = 1;
                var ctr = 0;
                var t = this;
                timer = setInterval(function() {
                    ctr++;
                    f.call(t, ctr);
                    fireStep = 2;
                }, timeout);
            })

            clearMousehold = function() {
                clearInterval(timer);
                if (fireStep == 1) f.call(this, 1);
                fireStep = 0;
            }

            jQuery(this).mouseout(clearMousehold);
            jQuery(this).mouseup(clearMousehold);
        })
    }
}

$.fn.extend({
    disableSelection: function() {
        this.each(function() {
            this.onselectstart = function() {
                return false;
            };
            this.unselectable = "on";
            $(this).css('-moz-user-select', 'none');
            $(this).css('-webkit-user-select', 'none');
        });
    }
});
4

1 回答 1

0

那么问题是,您希望多久检查一次用户输入的变化。当涉及到 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
}
于 2013-01-17T21:20:37.130 回答