javascript 키보드 이벤트 keydown keyup 를 위한 addEventListener 사용법
페이지 정보
작성자 관리자 (112.♡.173.204) 작성일 22-01-28 20:03 조회 1,847 댓글 0본문
## 기본사용법
```
window.onkeydown = (e) => console.log(e);
window.addEventListener("keydown", (e) => console.log(e));
```
## 화살표 함수에는 this 컨텍스트가 없습니다.
```
my_element.addEventListener('click', function (e) {
console.log(this.className) // logs the className of my_element
console.log(e.currentTarget === this) // logs `true`
})
my_element.addEventListener('click', (e) => {
console.log(this.className) // WARNING: `this` is not `my_element`
console.log(e.currentTarget === this) // logs `false`
})
```
## e.key
```
window.addEventListener("keydown", e => {
const key = document.getElementById(e.key);
console.log(key);
});
```
## input 또는 input[type=text] 가 아닌 곳에서만 실행하기
```
document.body.addEventListener("keyup", function(e) {
if ($('input').is(':focus') == false) {
console.log(e.key);
}
if ($('input[type=text]').is(':focus') == false) {
console.log(e.key);
}
});
```
## 참고
https://developer.mozilla.org/ko/docs/Web/API/EventTarget/addEventListener
https://www.w3schools.com/jsref/met_element_addeventlistener.asp
https://www.daleseo.com/js-key-events/
```
window.onkeydown = (e) => console.log(e);
window.addEventListener("keydown", (e) => console.log(e));
```
## 화살표 함수에는 this 컨텍스트가 없습니다.
```
my_element.addEventListener('click', function (e) {
console.log(this.className) // logs the className of my_element
console.log(e.currentTarget === this) // logs `true`
})
my_element.addEventListener('click', (e) => {
console.log(this.className) // WARNING: `this` is not `my_element`
console.log(e.currentTarget === this) // logs `false`
})
```
## e.key
```
window.addEventListener("keydown", e => {
const key = document.getElementById(e.key);
console.log(key);
});
```
## input 또는 input[type=text] 가 아닌 곳에서만 실행하기
```
document.body.addEventListener("keyup", function(e) {
if ($('input').is(':focus') == false) {
console.log(e.key);
}
if ($('input[type=text]').is(':focus') == false) {
console.log(e.key);
}
});
```
## 참고
https://developer.mozilla.org/ko/docs/Web/API/EventTarget/addEventListener
https://www.w3schools.com/jsref/met_element_addeventlistener.asp
https://www.daleseo.com/js-key-events/
추천0
댓글목록 0
등록된 댓글이 없습니다.