1

I'm wondering how to record keypresses on a blank html page, like, if A->B->C keys are pressed in a row (after eachother), then display a div or redirect the user. And if the user presses A->B-> but not C, then reset the array so the user has got to type it in again (from the start) in order for the desired action to be triggered.

4

2 回答 2

0

只是一个粗略的例子

    var checkArray = [],
    error = 'Enter the right combination !!',
    success = 'Success !!',
    $div = $('#div'),
    timer = 1000,
    timeout;

$(document).on('keyup', function (e) {
    if(timeout) clearTimeout(timeout);
    var keyPressed = e.keyCode;
    (keyPressed > 64 && keyPressed < 68) ? checkArray.push(keyPressed) 
                                         : checkArray = [];
    console.log(checkArray.join('-'));
    if (checkArray && checkArray.length === 3) {
        if (checkArray[0] === 65 && checkArray[1] === 66 
                                 && checkArray[2] === 67) {
            $div.text(success).addClass('a');
            timer = 2000;
        }
    } else {
        $div.text(error).removeClass('a');
    }
    timeout = setTimeout(reset, timer);
});

function reset() {
    timer =1000;
    checkArray = [];
    $div.text(error).removeClass('a');
}

检查小提琴

于 2013-05-23T01:06:06.177 回答
0

捕获 keydown 事件并将结果存储在全局变量中。将逻辑放入捕获事件中以执行所需的操作。

http://api.jquery.com/keydown/

于 2013-05-23T00:50:53.040 回答