KeyboardEvent.keyCode는 더 이상 사용되지 않습니다. 이것은 실제로 무엇을 의미합니까?
MDN에 따르면 .keyCode 속성을 사용 하지 않아야합니다. 더 이상 사용되지 않습니다.
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
W3 학교에서는이 사실이 무시되고 .keyCode
호환성을 위해서만 제공되며 DOM 이벤트 사양의 최신 버전이 .key
대신 속성을 사용하도록 권장 한다는 부수적 인 메모 만 있습니다.
문제는 .key
브라우저에서 지원하지 않는 것인데 무엇을 사용해야할까요? 내가 놓친 것이 있습니까?
공유 한 링크에 기록 된대로 세 가지 방법으로 처리 할 수 있습니다.
if (event.key !== undefined) {
} else if (event.keyIdentifier !== undefined) {
} else if (event.keyCode !== undefined) {
}
크로스 브라우저 지원을 원한다면 올바른 방법입니다.
이와 같은 것을 구현하면 더 쉬울 수 있습니다.
var dispatchForCode = function(event, callback) {
var code;
if (event.key !== undefined) {
code = event.key;
} else if (event.keyIdentifier !== undefined) {
code = event.keyIdentifier;
} else if (event.keyCode !== undefined) {
code = event.keyCode;
}
callback(code);
};
의 모든 또한 keyCode가 , , charCode 값 과 keyIdentifier가 : 사용되지 않습니다 및 비표준 기능입니다. Chrome 54에서 제거되고 Opera 41.0 은 FF에 일반 문자가있는 키 누르기 이벤트에서 0을 반환합니다.
charCode
keyIdentifier
keyIdentifier
keyCode
주요 속성 :
readonly attribute DOMString key
누른 키에 해당하는 키 속성 값을 보유합니다.
이 글을 쓰는 시점에서이 key
속성은 Firefox 52, Chrome 55, Safari 10.1, Opera 46의 모든 주요 브라우저에서 지원됩니다. Internet Explorer 11 제외 : 비표준 키 식별자 및 AltGraph의 잘못된 동작. 추가 정보
중요하거나 이전 버전과의 호환성이 필요한 경우 다음 코드와 같이 기능 감지를 사용할 수 있습니다.
을 주목하는 것이 key
값이 다르다 keyCode
거나 which
점에서 속성 : 그것은 키가 아닌 해당 코드의 이름이 포함됩니다. 프로그램에 문자 코드가 필요한 경우 charCodeAt()
. 단일 인쇄 가능한 문자의 charCodeAt()
경우 ArrowUp기회 와 같이 값에 여러 문자가 포함 된 키를 다루는 경우를 사용할 수 있습니다 . 특수 키를 테스트하고 그에 따라 조치를 취합니다. 그래서 키의 값의 테이블을 구현하는 시도와 해당 코드는 charCodeArr["ArrowUp"]=38
, charCodeArr["Enter"]=13
, charCodeArr[Escape]=27
... 등등, 살펴 보시기 바랍니다 키 값 과 해당 코드를
if(e.key!=undefined){
var characterCode = charCodeArr[e.key] || e.key.charCodeAt(0);
}else{
/* As @Leonid suggeted */
var characterCode = e.which || e.charCode || e.keyCode || 0;
}
/* ... code making use of characterCode variable */
이전 버전과의 호환성을 고려할 수 있습니다. 즉, 레거시 속성을 사용할 수있는 동안 사용하고 드롭 된 경우에만 새 속성으로 전환 할 수 있습니다.
if(e.which || e.charCode || e.keyCode ){
var characterCode = e.which || e.charCode || e.keyCode;
}else if (e.key!=undefined){
var characterCode = charCodeArr[e.key] || e.key.charCodeAt(0);
}else{
var characterCode = 0;
}
See also : the KeyboardEvent.code
property docs and some more details in this answer.
TLDR: I'd suggest that you should use the new event.key
and event.code
properties instead of the legacy ones. IE and Edge have support for these properties, but don't support the new key names yet. For them, there is a small polyfill which makes them output the standard key/code names:
https://github.com/shvaikalesh/shim-keyboard-event-key
I came to this question searching for the reason of the same MDN warning as OP. After searching some more, the issue with keyCode
becomes more clear:
The problem with using keyCode
is that non-English keyboards can produce different outputs and even keyboards with different layouts can produce inconsistent results. Plus, there was the case of
If you read the W3C spec: https://www.w3.org/TR/uievents/#interface-keyboardevent
In practice, keyCode and charCode are inconsistent across platforms and even the same implementation on different operating systems or using different localizations.
It goes into some depth describing what was wrong with keyCode
: https://www.w3.org/TR/uievents/#legacy-key-attributes
These features were never formally specified and the current browser implementations vary in significant ways. The large amount of legacy content, including script libraries, that relies upon detecting the user agent and acting accordingly means that any attempt to formalize these legacy attributes and events would risk breaking as much content as it would fix or enable. Additionally, these attributes are not suitable for international usage, nor do they address accessibility concerns.
So, after establishing the reason why the legacy keyCode was replaced, let's look at what you need to do today:
- All modern browsers support the new properties (
key
andcode
). - IE and Edge support an older version of the spec, which has different names for some keys. You can use a shim for it: https://github.com/shvaikalesh/shim-keyboard-event-key (or roll your own - it's rather small anyways)
- Edge has fixed this bug in the latest release (probably will be released in Apr 2018) - https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8860571/
- Refer to the list of event keys you can use: https://www.w3.org/TR/uievents-key/
MDN has already provided a solution:
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
window.addEventListener("keydown", function (event) {
if (event.defaultPrevented) {
return; // Should do nothing if the default action has been cancelled
}
var handled = false;
if (event.key !== undefined) {
// Handle the event with KeyboardEvent.key and set handled true.
} else if (event.keyIdentifier !== undefined) {
// Handle the event with KeyboardEvent.keyIdentifier and set handled true.
} else if (event.keyCode !== undefined) {
// Handle the event with KeyboardEvent.keyCode and set handled true.
}
if (handled) {
// Suppress "double action" if event handled
event.preventDefault();
}
}, true);
'programing' 카테고리의 다른 글
엔티티 프레임 워크 PostgreSQL (0) | 2020.10.22 |
---|---|
java.net.SocketException : 소프트웨어로 인한 연결 중단 : recv 실패 (0) | 2020.10.22 |
jQuery 선택기 성능을 향상시키는 좋은 방법? (0) | 2020.10.22 |
uniqid는 얼마나 고유합니까? (0) | 2020.10.22 |
System.Net.Http 대 Microsoft.Net.Http (0) | 2020.10.22 |