如何检查是否一次按下两个键?

时间:2015-02-20 19:35:07

标签: javascript hotkeys

window.onkeydown = function(e) {
    //enter key adds a task
    var code = e.keyCode || e.which;
    if(code === 13) {
        var taskName = document.getElementById("task_name").value;
        var dueDate = document.getElementById("due_date").value;
        $("#list").append("<div class='task'>" + taskName + "<textarea class='note_input' placeholder='Notes' rows='2'></textarea>" + "<br>" + "<div class='due'>" + "Due: " + dueDate + "</div>" + "</div>");
        $("h1").effect("pulsate", 1000);
    }
    //checking if alt and c keys are both pressed
    var clearKeys = {
alt: false,
  c: false,
    };
if (code === 18) {
    clearKeys.alt = true;
} else if (code === 67) {
    clearKeys.c = true;
}
if (clearKeys.alt === true && clearKeys.c === true) {
    $(".task").fadeOut("slow");
}
    //resetting the values of clearKeys.alt and clearKeys.c
    window.onkeyup = function(e) {
        var code = e.keyCode || e.which;
    if (code === 18) {
        clearKeys.alt = false;
    } else if (code === 67) {
        clearKeys.c = false;
    }
    };
};

我在JS Bin做了这个项目。 You can check it out here. 当我按下回车键时,它工作正常。但是,当我想清除列表(alt + c)时,它将无法正常工作。代码看起来很好,编辑器没有显示任何错误,所以我无法弄清楚哪里出错了。

1 个答案:

答案 0 :(得分:1)

window.onkeydown = function(e) {
    code == e.keyCode || e.which;
    if( e.altKey && code == 67 ) {
        //alt+c
    }
};