JavaScriptとjQuery、クロスブラウザを使用したキー押下イベント(F1〜F12)の処理

StackOverflow https://stackoverflow.com/questions/424407

質問

JavaScriptとjQueryを使用してF1〜F12キーを処理したい。

どのような落とし穴を避けるべきかわからず、現在Internet Explorer 8、Google Chrome、Mozilla FireFox 3以外のブラウザーで実装をテストすることはできません

完全なクロスブラウザソリューションへの提案はありますか?十分にテストされたjQueryライブラリーか、単なるバニラjQuery / JavaScriptのようなものですか?

役に立ちましたか?

解決

この種の質問に対する最良のソースは、このページです: http:// www。 quirksmode.org/js/keys.html

彼らが言うことは、キーコードはSafariでは奇妙であり、他のどこでも一貫しているということです(IEにはkeypressイベントはありませんが、keydownは機能すると信じています)。

他のヒント

ウィリアムは、ファンクションキーをハイジャックすることは一般的に悪い考えだと同意します。そうは言っても、この機能と他のキーボードを追加するショートカットライブラリを見つけました。ショートカットと組み合わせ、非常に滑らかな方法で。

単一のキーストローク:

shortcut.add("F1", function() {
    alert("F1 pressed");
});

キーストロークの組み合わせ:

shortcut.add("Ctrl+Shift+A", function() {
    alert("Ctrl Shift A pressed");
});

ファンクションキーの傍受が可能かどうかはわかりませんが、ファンクションキーを一緒に使用することは避けます。ファンクションキーはさまざまなタスクを実行するためにブラウザで使用されますが、その一部は非常に一般的です。たとえば、Linux上のFirefoxでは、少なくとも6つまたは7つのファンクションキーがブラウザで使用するために予約されています。

  • F1(ヘルプ)、
  • F3(検索)、
  • F5(更新)、
  • F6(フォーカスアドレスバー)、
  • F7(キャレットブラウジングモード)、
  • F11(全画面モード)、および
  • F12(Firebugを含むいくつかのアドオンで使用)

最悪の部分は、さまざまなオペレーティングシステム上のさまざまなブラウザが、さまざまなことに異なるキーを使用することです。これには多くの違いがあります。より安全で、あまり使用されないキーの組み合わせに固執する必要があります。

他の外部クラスがなくても、単純に使用して個人用のハックコードを作成できます

event.keyCode

他のすべての助けとして、このテストページはkeyCodeをインターセプトするためのものだと思います(イベントをテストするために、新しいfile.htmlをコピーアンドペーストするだけです)。

 <html>
 <head>
 <title>Untitled</title>
 <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
 <style type="text/css">
 td,th{border:2px solid #aaa;}
 </style>
 <script type="text/javascript">
 var t_cel,tc_ln;
 if(document.addEventListener){ //code for Moz
   document.addEventListener("keydown",keyCapt,false); 
   document.addEventListener("keyup",keyCapt,false);
   document.addEventListener("keypress",keyCapt,false);
 }else{
   document.attachEvent("onkeydown",keyCapt); //code for IE
   document.attachEvent("onkeyup",keyCapt); 
   document.attachEvent("onkeypress",keyCapt); 
 }
 function keyCapt(e){
   if(typeof window.event!="undefined"){
    e=window.event;//code for IE
   }
   if(e.type=="keydown"){
    t_cel[0].innerHTML=e.keyCode;
    t_cel[3].innerHTML=e.charCode;
   }else if(e.type=="keyup"){
    t_cel[1].innerHTML=e.keyCode;
    t_cel[4].innerHTML=e.charCode;
   }else if(e.type=="keypress"){
    t_cel[2].innerHTML=e.keyCode;
    t_cel[5].innerHTML=e.charCode;
   }
 }
 window.onload=function(){
   t_cel=document.getElementById("tblOne").getElementsByTagName("td");
   tc_ln=t_cel.length;
 }
 </script>
 </head>
 <body>
 <table id="tblOne">
 <tr>
 <th style="border:none;"></th><th>onkeydown</th><th>onkeyup</th><th>onkeypress</td>
 </tr>
 <tr>
 <th>keyCode</th><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>
 </tr>
 <tr>
 <th>charCode</th><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>
 </tr>
 </table>
 <button onclick="for(i=0;i<tc_ln;i++){t_cel[i].innerHTML='&nbsp;'};">CLEAR</button>
 </body>
 </html>

ここに実用的なデモがありますので、ここで試してみてください:

var t_cel, tc_ln;
if (document.addEventListener) { //code for Moz
  document.addEventListener("keydown", keyCapt, false);
  document.addEventListener("keyup", keyCapt, false);
  document.addEventListener("keypress", keyCapt, false);
} else {
  document.attachEvent("onkeydown", keyCapt); //code for IE
  document.attachEvent("onkeyup", keyCapt);
  document.attachEvent("onkeypress", keyCapt);
}

function keyCapt(e) {
  if (typeof window.event != "undefined") {
    e = window.event; //code for IE
  }
  if (e.type == "keydown") {
    t_cel[0].innerHTML = e.keyCode;
    t_cel[3].innerHTML = e.charCode;
  } else if (e.type == "keyup") {
    t_cel[1].innerHTML = e.keyCode;
    t_cel[4].innerHTML = e.charCode;
  } else if (e.type == "keypress") {
    t_cel[2].innerHTML = e.keyCode;
    t_cel[5].innerHTML = e.charCode;
  }
}
window.onload = function() {
  t_cel = document.getElementById("tblOne").getElementsByTagName("td");
  tc_ln = t_cel.length;
}
td,
th {
  border: 2px solid #aaa;
}
<html>

<head>
  <title>Untitled</title>
  <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
</head>

<body>
  <table id="tblOne">
    <tr>
      <th style="border:none;"></th>
      <th>onkeydown</th>
      <th>onkeyup</th>
      <th>onkeypress</td>
    </tr>
    <tr>
      <th>keyCode</th>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    <tr>
      <th>charCode</th>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
  </table>
  <button onclick="for(i=0;i<tc_ln;i++){t_cel[i].innerHTML='&nbsp;'};">CLEAR</button>
</body>

</html>

すごい簡単です。これを書くのは非難です、なぜ誰も前にそれを作らないのですか?

$(function(){
    //Yes! use keydown 'cus some keys is fired only in this trigger,
    //such arrows keys
    $("body").keydown(function(e){
         //well you need keep on mind that your browser use some keys 
         //to call some function, so we'll prevent this
         e.preventDefault();

         //now we caught the key code, yabadabadoo!!
         var keyCode = e.keyCode || e.which;

         //your keyCode contains the key code, F1 to F12 
         //is among 112 and 123. Just it.
         console.log(keyCode);       
    });
});

最新のブラウザとIE11向けのES6のソリューション(ES5へのトランスパイルを使用):

//Disable default IE help popup
window.onhelp = function() {
    return false;
};
window.onkeydown = evt => {
    switch (evt.keyCode) {
        //ESC
        case 27:
            this.onEsc();
            break;
        //F1
        case 112:
            this.onF1();
            break;
        //Fallback to default browser behaviour
        default:
            return true;
    }
    //Returning false overrides default browser event
    return false;
};

動作する場合はこのソリューションを試してください。

window.onkeypress = function(e) {
    if ((e.which || e.keyCode) == 116) {
        alert("fresh");
    }
}

angle.jsを使用してイベントを処理する場合、 ng-keydown を使用して、クロムの開発者で一時停止を防止する必要があります。

これは私には有効です。

if(code == 112){         alert(&quot; F1が押されました!!&quot;);         falseを返します。      }

F2-113、 F3-114、 F4-115、 フォート。

F1-F12キーをトラップする際の問題の1つは、デフォルトの機能もオーバーライドする必要があることです。以下は、 F1「ヘルプ」キーの実装例です。デフォルトのヘルプポップアップを防ぐオーバーライドがあります。このソリューションは、F2〜F12キー用に拡張できます 。また、この例では組み合わせキーを意図的にキャプチャしませんが、これも変更できます。

<html>
<head>
<!-- Note:  reference your JQuery library here -->
<script type="text/javascript" src="jquery-1.6.2.min.js"></script>
</head>
<body>
    <h1>F-key trap example</h1>
    <div><h2>Example:  Press the 'F1' key to open help</h2></div>
    <script type="text/javascript">
        //uncomment to prevent on startup
        //removeDefaultFunction();          
        /** Prevents the default function such as the help pop-up **/
        function removeDefaultFunction()
        {
            window.onhelp = function () { return false; }
        }
        /** use keydown event and trap only the F-key, 
            but not combinations with SHIFT/CTRL/ALT **/
        $(window).bind('keydown', function(e) {
            //This is the F1 key code, but NOT with SHIFT/CTRL/ALT
            var keyCode = e.keyCode || e.which;
            if((keyCode == 112 || e.key == 'F1') && 
                    !(event.altKey ||event.ctrlKey || event.shiftKey || event.metaKey))
             {
                // prevent code starts here:
                removeDefaultFunction();
                e.cancelable = true;
                e.stopPropagation();
                e.preventDefault();
                e.returnValue = false;
                // Open help window here instead of alert
                alert('F1 Help key opened, ' + keyCode);
                }
            // Add other F-keys here:
            else if((keyCode == 113 || e.key == 'F2') && 
                    !(event.altKey ||event.ctrlKey || event.shiftKey || event.metaKey))
             {
                // prevent code starts here:
                removeDefaultFunction();
                e.cancelable = true;
                e.stopPropagation();
                e.preventDefault();
                e.returnValue = false;
                // Do something else for F2
                alert('F2 key opened, ' + keyCode);
                }
        });
    </script>
</body>
</html>

同様のソリューション。これも同様に機能したかどうかをお知らせください。

次のようなjqueryでこれを実行できます。

        $("#elemenId").keydown(function (e) {
            if(e.key == "F12"){
                console.log(e.key);
            }

        });

ショートカットを追加:

$.Shortcuts.add({
    type: 'down',
    mask: 'Ctrl+A',
    handler: function() {
        debug('Ctrl+A');
    }
});

ショートカットへの反応を開始:

$.Shortcuts.start();

&#8220; another&#8221;へのショートカットを追加しますリスト:

$.Shortcuts.add({
    type: 'hold',
    mask: 'Shift+Up',
    handler: function() {
        debug('Shift+Up');
    },
    list: 'another'
});

アクティベート&#8220; another&#8221;リスト:

$.Shortcuts.start('another');
Remove a shortcut:
$.Shortcuts.remove({
    type: 'hold',
    mask: 'Shift+Up',
    list: 'another'
});

停止(イベントハンドラーのバインド解除):

$.Shortcuts.stop();


チュートリアル:
http://www.stepanreznikov.com/js-shortcuts/

この問題に対する私の解決策は次のとおりです。

document.onkeypress = function (event) {
    event = (event || window.event);
    if (event.keyCode == 123) { 
         return false;
    }
}

キーF12であるマジックナンバー 123 を使用。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top