source

키보드 이벤트키 코드가 사용되지 않습니다.이것은 실제로 무엇을 의미합니까?

nicesource 2022. 10. 25. 17:37
반응형

키보드 이벤트키 코드가 사용되지 않습니다.이것은 실제로 무엇을 의미합니까?

MDN에 따르면, 우리는 가장 확실한 방법으로.keyCode되지 않습니다권장되지 않습니다.

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode

W3 학교에서는, 이 사실이 경시되고 있고, 단지 다음과 같은 부수적인 언급이 있을 뿐이다..keyCode을 위해서만 되며 최신 에서는 DOM 사용을 합니다..key대신 속성을 지정합니다.

는 제는 the the the the the the the the the.key브라우저에서는 지원되지 않습니다.엇을을 사용 ?? ????가가 놓친 ?? ???

예를 들어 "Enter" 키를 클릭했는지 여부를 감지하려면 다음 절차를 따릅니다.

대신

event.keyCode === 13

처럼 하다

event.key === 'Enter'

공유한 링크에 기재되어 있기 때문에, 세 가지 방법으로 대응할 수 있습니다.

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);
};

TLDR: 저는 당신이 새로운 것을 사용하는 것을 제안합니다.event.key ★★★★★★★★★★★★★★★★★」event.code기존 속성이 아닌 속성입니다.IE 및 Edge는 이러한 속성을 지원하지만 새 키 이름은 아직 지원하지 않습니다.이러한 사용자에게는 표준 키/코드 이름을 출력할 수 있는 작은 폴리필이 있습니다.

https://github.com/shvaikalesh/shim-keyboard-event-key


OP와 같은 MDN 경고의 이유를 찾아 이 질문을 하게 되었습니다.해 본 , 「 」에 , 「 」의 문제,keyCode보다 명확해집니다.

「 」를 keyCode영어 이외의 키보드는 다른 출력을 생성할 수 있으며 레이아웃이 다른 키보드도 일관되지 않은 결과를 생성할 수 있습니다. 외에도 '나다', '아니다', '아니다'의 경우도 있었습니다.

W3C 스펙을 읽는 경우:https://www.w3.org/TR/uievents/ #interface-interface-interface-interface event

실제로 keyCode와 charCode는 플랫폼 간에 일관성이 없습니다.또, 다른 operating system 또는 다른 현지화를 사용하고 있는 경우에서도, 같은 실장이 행해지고 있습니다.

이 어떤 하겠습니다.keyCode: https://www.w3.org/TR/uievents/ #syslog-key-attributes

이러한 기능은 공식적으로 지정되어 있지 않으며 현재 브라우저의 실장은 크게 다릅니다.스크립트 라이브러리를 포함한 많은 레거시 콘텐츠는 사용자 에이전트를 검출하고 그에 따라 동작해야 하기 때문에 이러한 레거시 속성 및 이벤트를 공식화하려고 하면 수정 또는 활성화될 수 있는 만큼의 콘텐츠가 파손될 위험이 있습니다.게다가 이러한 속성은, 국제적인 사용에는 적합하지 않고, 액세스성의 염려에도 대응하지 않습니다.

레거시 keyCode가 교체된 이유를 파악한 후 오늘 수행해야 할 작업을 살펴보겠습니다.

  1. 합니다(「」 「」 「」 「」 「」 「」key ★★★★★★★★★★★★★★★★★」code를 참조해 주세요.
  2. IE 및 Edge는 일부 키에 대해 이름이 다른 이전 버전의 규격을 지원합니다.심을 사용할 수 있습니다.https://github.com/shvaikalesh/shim-keyboard-event-key (혹은 직접 롤링을 할 수도 있습니다.어차피 크기는 작습니다)
  3. Edge는 최신 릴리스(2018년 4월 출시 예정)에서 이 버그를 수정했습니다.https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8860571/
  4. 사용할 수 있는 이벤트키 목록을 참조해 주세요.https://www.w3.org/TR/uievents-key/

또한 charCodekeyIdentifier는 모두 폐지됩니다.
charCode ★★★★★★★★★★★★★★★★★」keyIdentifier을 사용하다
keyIdentifierChrome 54 오페라 41.0
keyCode FF 의 통상의 키 에 대해서 0 을 합니다.FF 에 、 0 을을 。

주요 속성은 다음과 같습니다.

 readonly attribute DOMString key

누른 키에 해당하는 키 속성 값을 보유합니다.

쓸 때 로선요.key속성은 Firefox 52, Chrome 55, Safari 10.1, Opera 46의 모든 주요 브라우저에서 지원됩니다.비표준식별자 및 AltGraph에서의 잘못된 동작을 가진 Internet Explorer 11은 제외합니다. 상세 정보
이것이 경우 할 수 : " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " "

해 주세요.keykeyCode ★★★★★★★★★★★★★★★★★」which[그것의 속성] : 키 [ [ [ [ [ [ [ [ [ [ [.캐릭터의 는, 이 코드를 할 수 .charCodeAt(). 한 한 는 .를 사용할 수 charCodeAt()값에 여러 문자가 포함된 키를 취급하는 경우(예: 특수 키를 테스트하고 그에 따라 조치를 취합니다).따라서 키 값과 해당 코드의 표를 구현해 보십시오.charCodeArr["ArrowUp"]=38,charCodeArr["Enter"]=13 ,charCodeArr[Escape]=27...등, Key Values 와 대응하는 코드를 봐 주세요.

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;
    }

」도 참조해 .KeyboardEvent.code속성 문서 및 답변의 몇 가지 세부 정보를 참조하십시오.

MDN은 이미 다음과 같은 솔루션을 제공하고 있습니다.

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);

e.charCode

<input
  onChange={(e) => setToken(e.target.value)}
  type="text"
  value={token}
  onKeyPress={(e) => {
    if (e.charCode === 13) {
      verifyLoginF()
    }
  }}
/>

여기에 이미지 설명 입력

지금 바로 사용하세요.e.key === 'Enter'

여기에 이미지 설명 입력

여기서는 keyCode 대신 key값을 사용하고 실패 시 keyCode를 사용하도록 제안했습니다.이 Atribute의 값이 호환되지 않기 때문에 이것만으로는 충분하지 않습니다.새로운 키에는 다음과 같은 제어 키 문자열이 포함되어 있습니다.ArrowUp. 단, keyCode에는 사소한 코드만 포함됩니다.

String.fromCharCode(event.keyCode)

인쇄할 수 없는 문자가 생성됩니다.인쇄 가능한 문자를 위한 솔루션은 다음과 같습니다.

element.keydown((event) => {
    var symbolPressed;
    //cross browser
    if (event.key !== undefined) {
        symbolPressed = event.key; //Here control characters represented as String like: ArrowUp
        if (symbolPressed.length > 1) return; //filter out control characters
    } else if (event.keyCode !== undefined) {
        symbolPressed = String.fromCharCode(event.keyCode); //Here control chars represented as one char string
    }
    //Update this regex if you need other characters
    if (!symbolPressed.match(/[A-z0-9\s]/)) return;
    console.log(symbolPressed);
});

또한 인쇄할 수 없는 컨트롤 문자가 필요한 경우 조건을 업데이트하고 그에 따라 정규식을 수행해야 합니다.

이벤트에 대한 키 누르기와 키 누르기를 사용합니다.스위치 [CARTER 코드]또는 [KEYCODE]입니다.

 function myKey(event){
 
  var keycode = event.keyCode;  //key code variant 1, not recomendate
  var keywhic = event.which;    //key code variant 2, nice worked 
  var unicode = event.key;      //string name code, nice worked  
  var chacode = event.charCode; //works onkeypress="myKey(event)"
  var metakey = event.metaKey;  //true false, winKey or macComand
  
  document.getElementById("demo").innerHTML = keycode+" "+keywhic+" "+unicode+" "+chacode+" "+metakey;
}
<!DOCTYPE html>
<html>
<body onkeydown="myKey(event)"> <!--onkeypress="myKey(event)"-->

<h1 id="demo">Keyboard Buttons click me and test the keyboard</h1>
<script>
 //function myKey(event){
 //paste code
 //}
</script>
</body>
</html>

사용할 수 있습니다.

parseInt(event.key, radix: 10)
(e)=>{
  e.key === 'Escape';
}

와 같다

(e)=>{
  e.keyCode === 27;
}

두 번째 것을 사용하는 것이 좋습니다.

언급URL : https://stackoverflow.com/questions/35394937/keyboardevent-keycode-deprecated-what-does-this-mean-in-practice

반응형