programing

JavaScript 및 jQuery를 사용한 크로스 브라우저 키 누르기 이벤트(F1-F12) 처리

mailnote 2023. 9. 3. 16:29
반응형

JavaScript 및 jQuery를 사용한 크로스 브라우저 키 누르기 이벤트(F1-F12) 처리

자바스크립트와 jQuery를 이용하여 F1-F12 키를 처리하고 싶습니다.

피해야 할 함정이 무엇인지 확신할 수 없으며, 현재 Internet Explorer 8, Google Chrome 및 Mozilla FireFox 3 이외의 다른 브라우저에서 구현을 테스트할 수 없습니다.

전체 크로스 브라우저 솔루션에 대한 제안 사항이 있습니까?잘 테스트된 jQuery 라이브러리나 바닐라 jQuery/JavaScript 같은 것?

일반적으로 기능 키를 가로채는 것은 나쁜 생각이라는 윌리엄의 말에 동의합니다.그렇긴 하지만, 저는 이 기능뿐만 아니라 다른 키보드 단축키와 조합을 매우 교묘하게 추가한 바로 가기 라이브러리를 찾았습니다.

단일 키 입력:

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

키 입력 조합:

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

이런 종류의 질문에 대해 제가 가지고 있는 가장 좋은 출처는 이 페이지입니다: http://www.quirksmode.org/js/keys.html .

그들이 말하는 것은 Safari에서 키 코드가 이상하고 다른 모든 곳에서 일관성이 있다는 것입니다(IE에서는 키 프레스 이벤트가 없지만 키다운이 작동한다고 생각합니다).

함수 키를 가로채는 것이 가능할지는 모르겠지만 함수 키를 함께 사용하는 것은 피하겠습니다.기능 키는 브라우저에서 다양한 작업을 수행하는 데 사용되며, 일부는 매우 일반적입니다.예를 들어 Linux의 Firefox에서는 적어도 6개 또는 7개의 기능 키가 브라우저에서 사용하도록 예약되어 있습니다.

  • F1(도움말),
  • F3(검색),
  • F5(새로 고침),
  • F6(초점 주소 표시줄),
  • F7(카트 탐색 모드),
  • F11(전체 화면 모드),
  • F12(Firebug를 포함한 여러 추가 기능에서 사용)

가장 나쁜 점은 다른 운영 체제의 다른 브라우저가 다른 작업에 다른 키를 사용한다는 것입니다.그것은 설명할 수 있는 많은 차이점입니다.일반적으로 사용되지 않는 안전한 키 조합을 사용해야 합니다.

그것은 매우 간단합니다.

$(function(){
    //Yes! use keydown because some keys are fired only in this trigger,
    //such arrows keys
    $("body").keydown(function(e){
         //well so 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.
         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);       
    });
});

다른 외부 클래스 없이 단순히 사용하여 개인 해킹 코드를 만들 수 있습니다.

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>

최신 브라우저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;
};

이것은 나에게 효과가 있습니다.

if(code ==112) { alert("F1 was pressed!!"); return false; }

F2 - 113, F3 - 114, F4 - 115 등입니다.

Vanilla Javascript 및 KeyboardEvents를 사용할 수 있습니다. keydown,keypress또는keyup.

event.key(권장) 또는 event.code를 사용하여 다음과 같은 키 이름과 비교합니다.event.key === "F1".

기능 키로 작업할 때 기본 동작을 억제할 수 있습니다(창에서는 대부분의 기능 키가 브라우저에서 사용됨).이는 전화를 통해 달성할 수 있습니다.preventDefault()에서keydown이벤트. 당신이 듣고 싶어도.keyup전화해야 하는 이벤트preventDefault()에서keydown이벤트. 브라우저 바로 가기가 해당 이벤트에 바인딩되어 있기 때문입니다.명심해, 그 소명은preventDefault()keydown 키 누르기 이벤트도 억제합니다.

document
  .addEventListener("keydown", e => {
    if(e.key === "F1") {
      // Suppress default behaviour 
      // e.g. F1 in Microsoft Edge on Windows usually opens Windows help
      e.preventDefault()
    }
  })

document
  .addEventListener("keyup", e => {
    if(e.key === "F1") {
      // Handle the keyup event
      doSomething()
    }
  })

F1-F12 키를 트래핑할 때 발생하는 문제 중 하나는 기본 기능도 재정의해야 한다는 것입니다.다음은 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>

저는 이것을 개발할 때 관련 SO 기사에서 비슷한 솔루션을 빌렸습니다.이것이 당신에게도 효과가 있었는지 알려주세요.

이 이벤트 수신기를 추가합니다.

function keyDown(e)
{
    let charStr, key = e.which || e.keyCode;
    if (key >= 112 && key <= 123)
    {
        e.preventDefault();
        e.stopPropagation();
        charStr = "F" + (key - 111);
        switch (charStr)
        {
            case "F1":
                alert("F1");
                break;
            case "F2":
                alert("F2");
                break;
            default:
                alert("Other F key");
                break;
        }
    }
}

document.addEventListener('keydown', keyDown);

이것은 브라우저 호환성이 매우 좋습니다.나는 인터넷 익스플로러 8이나 모질라 파이어폭스 3에 대해서는 잘 모르지만, 2022년에는 여전히 거의 관련이 없습니다.

이 문제에 대한 저의 해결책은 다음과 같습니다.

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

마법의 숫자와 함께123키 F12입니다.

앱이 원격으로 모바일에 친숙하지 않다는 점을 고려하십시오.

바로 가기 추가:

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

바로 가기에 대한 대응 시작:

$.Shortcuts.start();

"다른" 목록에 바로 가기 추가:

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

다른 목록 활성화:

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

중지(이벤트 처리기 바인딩 해제):

$.Shortcuts.stop();


자습서:
http://www.stepanreznikov.com/js-shortcuts/

효과가 있으면 이 솔루션을 사용해 보십시오.

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

다음과 같은 jquery로 이 작업을 수행할 수 있습니다.

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

        });

언급URL : https://stackoverflow.com/questions/424407/handling-key-press-events-f1-f12-using-javascript-and-jquery-cross-browser

반응형