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 に答える