【问题标题】:Detect which key was pressed in javascript?检测在javascript中按下了哪个键?
【发布时间】:2016-01-31 04:07:18
【问题描述】:

我检查了以下内容:

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

而且这些都不起作用。 在我按下某些字符并按 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' 代替

【问题讨论】:

    标签: javascript html sapui5


    【解决方案1】:

    要使用的正确事件是“keydown”。 使用keyCodewhich 获取按键:

    (e.keyCode||e.which)

    使用此示例:

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

    【讨论】:

      【解决方案2】:
      <!DOCTYPE html>
      <html>
      <body>
      <script>
          window.addEventListener("keydown", function(e) { 
              //your code here
          });
      </script>
      </body>
      </html>
      

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

        • 添加了这个:` window.addEventListener("keydown", function(e) { if (e.keyCode === 32 ) { //eslint-disable-line e.preventDefault(); 控制台.log("按下空格"); } }); `这仍然不起作用:(
        • 嗨@pokrak94,你在哪里添加了这个,你使用的是什么浏览器? JSbin 示例对您有用吗?
        • js-bin 示例在给出的示例中对我有用。我刚刚用我在第一条评论中给你的代码替换了我原来的键检测代码。哦,我正在使用 Chrome。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-12-20
        • 2020-12-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多