JavaScript 및 jQuery, 크로스 브라우저를 사용하여 키 누르기 이벤트 (F1-F12) 처리
JavaScript와 jQuery를 사용하여 F1-F12 키를 처리하고 싶습니다.
현재 Internet Explorer 8, Google Chrome 및 Mozilla FireFox 3 이외의 다른 브라우저에서 구현을 테스트 할 수 없습니다.
완전한 크로스 브라우저 솔루션에 대한 제안이 있습니까? 잘 테스트 된 jQuery 라이브러리 또는 단순한 jQuery / JavaScript와 같은 것입니까?
이런 종류의 질문에 대한 가장 좋은 소스는 다음 페이지입니다. http://www.quirksmode.org/js/keys.html
그들이 말하는 것은 키 코드가 Safari에서 이상하고 다른 모든 곳에서 일관 적이라는 것입니다 (IE에는 키 누르기 이벤트가 없지만 키 다운이 작동합니다).
William의 의견에 동의합니다. 즉, 이 기능과 다른 키보드 단축키 및 조합을 매우 매끄럽게 추가 하는 단축키 라이브러리를 찾았 습니다 .
단일 키 입력 :
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가 포함 된 여러 애드온에서 사용)
최악의 부분은 운영마다 다른 브라우저가 서로 다른 키를 사용한다는 것입니다. 그것은 설명해야 할 많은 차이점입니다. 더 안전하고 덜 일반적으로 사용되는 키 조합을 고수해야합니다.
와우 아주 간단합니다. 이 글을 쓰는 것이 비난인데 왜 전에는 아무도 만들지 갑자기나요?
$(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);
});
});
다른 외부 클래스없이 간단히 다음을 사용하여 개인 해킹 코드를 만들 수 있습니다.
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> </td><td> </td><td> </td>
</tr>
<tr>
<th>charCode</th><td> </td><td> </td><td> </td>
</tr>
</table>
<button onclick="for(i=0;i<tc_ln;i++){t_cel[i].innerHTML=' '};">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> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<th>charCode</th>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
<button onclick="for(i=0;i<tc_ln;i++){t_cel[i].innerHTML=' '};">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 등 요새입니다.
작동하는 경우이 솔루션을 시도하십시오.
window.onkeypress = function(e) {
if ((e.which || e.keyCode) == 116) {
alert("fresh");
}
}
이벤트 처리를 위해 angular.js를 사용할 때는 크롬에서 ng-keydown
방지 pause in developer
를 위해 사용해야합니다 .
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 기사에서 유사한 솔루션 을 빌 렸습니다 . 이것이 당신에게도 효과가 있는지 알려주십시오.
다음과 같이 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();
"다른"목록에 바로 가기 추가 :
$.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/
이 문제에 대한 나의 해결책은 다음과 같습니다.
document.onkeypress = function (event) {
event = (event || window.event);
if (event.keyCode == 123) {
return false;
}
}
123
열쇠 인 매직 넘버 로 F12.
'ProgramingTip' 카테고리의 다른 글
ng-click으로 $ event를 자동으로 전달 하시겠습니까? (0) | 2020.11.11 |
---|---|
스위프트 상수 : Struct 또는 Enum (0) | 2020.11.11 |
단일성을 사용하여 명명 된 말을 생성자에 어떻게하면? (0) | 2020.11.11 |
C ++ 0x와 C ++ 11의 차이점은 무엇입니까? (0) | 2020.11.11 |
SQL 열 정의 : 통화이고 null이 아닙니까? (0) | 2020.11.11 |