簡體   English   中英

檢測在javascript中按下了哪個鍵?

[英]Detect which key was pressed in javascript?

我檢查了以下內容:

如何找出按下了哪個字符鍵?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+檢測+哪個+鍵+是+按下+輸入+Javascript

而且都沒有工作。 在我按一些字符並按 Enter 后,我當前的代碼給了我一個警告,說“未定義”。

我目前的代碼:

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

嗨,請看這個例子,它包含一個帶有多個鍵的例子。 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>

正確使用的事件是“keydown”。 獲取與按下按鍵keyCodewhich有這樣:

(e.keyCode||e.which)

使用此示例:

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