简体   繁体   English

检测在javascript中按下了哪个键?

[英]Detect which key was pressed in javascript?

I checked the following:我检查了以下内容:

How to find out what character key is pressed? 如何找出按下了哪个字符键?http://www.javascriptkit.com/javatutors/javascriptkey2.shtml http://www.w3schools.com/jsref/event_key_keycode.asp http://forums.asp.net/t/1782329.aspx?How+to+detect+which+Key+is+pressed+in+Javascripthttp://www.javascriptkit.com/javatutors/javascriptkey2.shtml http://www.w3schools.com/jsref/event_key_keycode.asp http://forums.asp.net/t/1782329.aspx?How+to+检测+哪个+键+是+按下+输入+Javascript

And none of it is working.而且都没有工作。 My current code gives me an alert saying "undefined" after I press some characters and press enter.在我按一些字符并按 Enter 后,我当前的代码给了我一个警告,说“未定义”。

My current code:我目前的代码:

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta http-equiv='Content-Type' content='text/html;charset=UTF-8'/>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>    
<script src="https://sapui5.netweaver.ondemand.com/resources/sap-ui-core.js" id="sap-ui-bootstrap" data-sap-ui-libs="sap.ui.ux3,sap.ui.commons,sap.ui.table, sap.ui.richtexteditor" data-sap-ui-theme="sap_goldreflection" data-sap-ui-language="en">
</script>

<script>
function showKeyPress(evt)
{
alert("onkeypress handler: \n"
      + "keyCode property: " + evt.keyCode + "\n"
      + "which property: " + evt.which + "\n"
      + "charCode property: " + evt.charCode + "\n"
      + "Character Key Pressed: "
      + String.fromCharCode(evt.charCode) + "\n"
     );
}
var oInput2 = new sap.ui.richtexteditor.RichTextEditor({
    id : 'ta',
    tooltip : 'This is a tooltip',
    width: '100%',
    rows : 4,
    wrapping : false,
    change: function(e)
    {
        var code =  oInput2.getValue();
        //console.log(code);
        var regex = /(<([^>]+)>)/ig
    //  var result = body.replace(regex, "");
        code = code.replace(/&nbsp;|/g, '');
        code = code.replace(regex,"");
        //console.log(code);
        var ex = code.split(' ');
        //console.log(ex);
        var array = ["&lt;?","&lt;?php","?&gt;"];
        var keyWords = ['__halt_compiler', 'abstract', 'and', 'array', 'as', 'break', 'callable', 'case', 'catch', 'class', 'clone', 'const', 'continue', 'declare', 'default', 'die', 'do', 'echo', 'else', 'elseif', 'empty', 'enddeclare', 'endfor', 'endforeach', 'endif', 'endswitch', 'endwhile', 'eval', 'exit', 'extends', 'final', 'for', 'foreach', 'function', 'global', 'goto', 'if', 'implements', 'include', 'include_once', 'instanceof', 'insteadof', 'interface', 'isset', 'list', 'namespace', 'new', 'or', 'print', 'private', 'protected', 'public', 'require', 'require_once', 'return', 'static', 'switch', 'throw', 'trait', 'try', 'unset', 'use', 'var', 'while', 'xor'];
        var colored = "";
        ex.forEach(function(entry){
            //alert(array.indexOf('<p>'+entry+'</p>'));
            alert(KeyboardEvent.location);
            var num = 0;
            if(array.indexOf(entry) > -1)
            {
                num = 1;
            }
            if(keyWords.indexOf(entry) > -1)
            {
                num = 2;
            }
            switch(num)
            {
                case 1:
                    colored += "<span style='color:red'> "+entry+"</span> ";
                    break;
                case 2:
                    colored += '<span style="color:blue"> '+entry+'</span> ';
                    break;
                default:
                    colored += entry+ ' ';
            }
        })

        //console.log(colored);
        oInput2.setValue(colored);

    }
    });
//  function cleanCode(a)
//  {
//      a = a.replace(/<span style="color: red;">/g, '');
//      return a;
//  }
    oInput2.placeAt('content');

oInput2.onkeypress = function(event)
{
    if(event.keyCode == 32)
    {
        alert("space");
        console.log("space");
    }
}

        </script>
        <script type="text/javascript">
        function myKeyPress(e){

            var keynum;

            if(window.event){ // IE                 
                keynum = e.keyCode;
            }else
                if(e.which){ // Netscape/Firefox/Opera                  
                    keynum = e.which;
                 }
            alert(String.fromCharCode(keynum));
        }
</script>
    </head>
    <body class="sapUiBody" onkeydown="myKeyPress(e);">
        <div id="content"></div>
    </body>
</html>

also I have this message (warning) in the console:我在控制台中也有这条消息(警告):

'KeyboardEvent.keyLocation' is deprecated.不推荐使用“KeyboardEvent.keyLocation”。 Please use 'KeyboardEvent.location' instead请改用“KeyboardEvent.location”

Hi please look at this example, it contains an example with multiple keys.嗨,请看这个例子,它包含一个带有多个键的例子。 The code in html should be sufficient: html中的代码应该足够了:

   window.addEventListener("keydown", function(e) {
    //your code here
   });
<!DOCTYPE html>
<html>
<body>
<script>
    window.addEventListener("keydown", function(e) { 
        //your code here
    });
</script>
</body>
</html>

The right event to use is "keydown".正确使用的事件是“keydown”。 Get the key pressed with keyCode or which with this way:获取与按下按键keyCodewhich有这样:

(e.keyCode||e.which)

Example using this:使用此示例:

window.onkeydown=function(e){
     alert(((e.keyCode||e.which)==32)?'Spacebar pressed.':'Spacebar was not pressed.');
}

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

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