JavaScript

[JavaScript] 마우스, 키보드 이벤트

코딩 수달 2022. 7. 27. 00:46
728x90
반응형

이벤트

이벤트 트리거
이벤트를 발생시키는 신호
 ex) click,dblclick,mouseover,keydown,keypress,...

 

이벤트 핸들러

실제 발생되는 이벤트 내용


html에서 사용하는 요소에게 이름을 부여하는 방식
- id
- class

- name

 

< 마우스 이벤트 > 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>마우스 이벤트</title>
<style type="text/css">
   #box {
      width: 100px;
      height: 100px;
      cursor: pointer;
      background-color: coral;
   }
</style>
</head>
<body>
 
<script type="text/javascript">
   function func1(obj){
      obj.style.backgroundColor="lightblue";
   }
   
   function func2(obj){
      obj.style.backgroundColor="lightgray";
   }
</script>
 
<div id="box" onmouseover="func1(this)" onmouseout="func2(this)"></div>
 
</body>
</html>
cs

onmouseover : 마우스가 올라갔을 때 이벤트 발생

onmouseout : 마우스가 떨어졌을 때 이벤트 발생

이벤트 시작 전 : 코랄색

마우스 올라갔을 때 : 하늘색

마우스 올라간 뒤 : 회색 

 

<키보드 이벤트> 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>키보드 이벤트</title>
<style type="text/css">
    input [name="test"]{
    border: 3px solid black;
    }
 
</style>
</head>
<body>
<script type="text/javascript">
    function func(event){
        console.log(event.keyCode);
    }
</script>
 
<input type="text" onkeydown="func(event)" name="" placeholder="console 확인">
 
</body>
</html>
cs

 

onkeydown : 키보드 입력 했을 때 이벤트 발생

입력한 값에 따라서 콘솔창에 key값이 나온다. 

 

< 전화번호를 입력했을때 뒷자리를 *로 표기> 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>예제풀이</title>
</head>
<body>
<script type="text/javascript">
   var input=prompt('010-xxxx-xxxx의 형태로 입력해주세요.');
   var arr=input.split('-');
   console.log(arr[0]+'-'+arr[1]+'-****');
   
   function func(event){
      if(event.keyCode==13){
         alert(event.target.value);
      }
   }
</script>
<input type="text" onkeydown="func(event)">
</body>
</html>
cs

 

split()함수 : 괄호 안의 내용을 기준으로 문자열을 나눌 때 사용 

 

 

 

 

 

728x90
반응형