检测javascript中按下了哪个键?

时间:2015-10-30 16:44:52

标签: javascript html sapui5

我检查了以下内容:

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+Javascript

它都不起作用。 在我按下一些字符并按回车键后,我当前的代码给了我一个警告“未定义”。

我目前的代码:

<!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>

我在控制台中也有此消息(警告):

  

'KeyboardEvent.keyLocation'已弃用。请用   'KeyboardEvent.location'而不是

3 个答案:

答案 0 :(得分:1)

嗨,请查看this示例,它包含一个包含多个键的示例。 html中的代码应该足够了:

   window.addEventListener("keydown", function(e) {
    //your code here
   });

答案 1 :(得分:0)

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

答案 2 :(得分:0)

正确使用的事件是&#34; keydown&#34;。 通过以下方式使用keyCodewhich按下键:

(e.keyCode||e.which)

使用此示例:

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