0

我的网站上有一个html5游戏,我阻止了AWSD keys和的操作SPACEBAR。问题是游戏下的评论部分无法使用(更具体地说是AWSD keys or SPACEBAR);

有任何想法吗?

这是我的代码,它很菜鸟。忽略评论。

这是引用关键事件的函数:

function slide2() {
        drawSlide2();
        document.removeEventListener('click', mouseNext, false);
        document.addEventListener('click', mouseNext2, false);
        document.addEventListener('keydown', startCheckKeyDown2, false);
        document.addEventListener('keyup', startCheckKeyUp2, false);
        document.removeEventListener('keydown', startCheckKeyDown1, false);
        document.removeEventListener('keyup', startCheckKeyUp1, false);
}

awsd 函数的事件侦听器

function playGame() {
    drawBg(); 
    startLoop(); //we call this when the game loads
    updateHUD();
    document.addEventListener('keydown', checkKeyDown, false);
    document.addEventListener('keyup', checkKeyUp, false);
    notMoving = false;
}

这是我的 keyCode 函数

function checkKeyDown(e) { //e is a keyword or something we use to describe an event, whenever 
    var keyID = e.keyCode || e.which; //this is like an if statment except in one line // it gets the keyID from the differing ID's from different browsers. cross-browser 
    if (keyID === 38 || keyID === 87) {  //  **** Up arrow and W *****
        jet1.isUpKey = true;
        e.preventDefault(); //prevents default actions of the up and w key funcions, like scrolling up and down
    }
    if (keyID === 39 || keyID === 68) {  //  **** RIGHT & W *****
        jet1.isRightKey = true;
        e.preventDefault(); 
    }
    if (keyID === 40 || keyID === 83) {  //  **** DOWN or S *****
        jet1.isDownKey = true;
        e.preventDefault(); 
    }
    if (keyID === 37 || keyID === 65) {  //  **** LEFT or A *****
        jet1.isLeftKey = true;
        e.preventDefault(); 
    }
    if (keyID === 32) {  //  **** SPACEBAR *****
        jet1.isSpacebar = true;
        e.preventDefault(); 
    }
} 

function checkKeyUp(e) { 
    var keyID = e.keyCode || e.which; 
    if (keyID === 38 || keyID === 87) {  //  **** Up arrow and W *****
        jet1.isUpKey = false;
        e.preventDefault(); 
    }
    if (keyID === 39 || keyID === 68) {  //  **** RIGHT & W *****
        jet1.isRightKey = false;
        e.preventDefault(); 
    }
    if (keyID === 40 || keyID === 83) {  //  **** DOWN or S *****
        jet1.isDownKey = false;
        e.preventDefault(); 
    }
    if (keyID === 37 || keyID === 65) {  //  **** LEFT or A *****
        jet1.isLeftKey = false;
        e.preventDefault(); 
    }
    if (keyID === 32) {  //  **** SPACEBAR *****
        jet1.isSpacebar = false;
        e.preventDefault(); 
    }
}
4

1 回答 1

0

快速回答是让画布处理它自己的关键事件:

  1. 启用画布以获取 keydown 事件:yourCanvas.setAttribute("tabindex",0);
  2. 监听 keydown 事件:yourCanvas.addEventListener('keydown',handleKeydown,true);
  3. 在handleKeydown中,防止事件冒泡:event.preventDefault();
于 2013-06-26T01:29:57.133 回答