简体   繁体   English

将键码用于“ +”和“-”

[英]Using keycodes for '+' and '-'

Hi I have the following code in my Cesium project and would like to know how I can use other keys other than the characters. 嗨,我在Cesium项目中有以下代码,并且想知道如何使用除字符以外的其他键。 Here is what I have at the minute: 这是我目前的情况:

function getFlagForKeyCode(keyCode) {
switch (keyCode) {
case 'W'.charCodeAt(0):
    return 'moveForward';
case 'S'.charCodeAt(0):
    return 'moveBackward';
case 'Q'.charCodeAt(0):
    return 'moveUp';
case 'E'.charCodeAt(0):
    return 'moveDown';
case 'D'.charCodeAt(0):
    return 'moveRight';
case 'A'.charCodeAt(0):
    return 'moveLeft';
default:
    return undefined;
}

} }

I want to be able to use the - and + keys. 我希望能够使用-和+键。 How can I achieve this? 我该如何实现?

If your keyCode comes from keyup/keydown event, you need to do something like this: 如果您的keyCode来自keyup / keydown事件,则需要执行以下操作:

document.addEventListener("keydown", function(e){
    if ((e.shiftKey && e.keyCode == 187) || e.keyCode == 107) {
        e.keyCode = 43; // 43 - char code for "+"
    }

    if (e.keyCode == 189 || e.keyCode == 109) {
        e.keyCode = 45; // 45 - char code for "-"
    }

    getFlagForKeyCode(e.keyCode);

}, false);

And extend your getFlagForKeyCode function 并扩展您的getFlagForKeyCode函数

function getFlagForKeyCode (keyCode) {
    switch (keyCode) {
    case 'W'.charCodeAt(0):
        return 'moveForward';
    case 'S'.charCodeAt(0):
        return 'moveBackward';
    case 'Q'.charCodeAt(0):
        return 'moveUp';
    case 'E'.charCodeAt(0):
        return 'moveDown';
    case 'D'.charCodeAt(0):
        return 'moveRight';
    case 'A'.charCodeAt(0):
        return 'moveLeft';
    case '+'.charCodeAt(0):
        // return what you need
    case '-'.charCodeAt(0):
        // return what you need
    default:
        return undefined;
    }
}

Up, down, left and right use the arrow keys which are codes 37-40 and the + and - keys are 187 and 189: 向上,向下,向左和向右使用箭头键(代码37-40),而+和-键分别为187和189:

function getFlagForKeyCode(keyCode) {
switch (keyCode) {
case 187:
    return 'moveForward';
case 189:
    return 'moveBackward';
case 38:
    return 'moveUp';
case 40:
    return 'moveDown';
case 39:
    return 'moveRight';
case 37:
    return 'moveLeft';
default:
    return undefined;
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM