스터디/개인스터디

[JS] 키보드 이벤트(onkeydown, onkeyup, onkeypress)

d0201d 2020. 12. 18. 23:50

onkeydown

- 키를 눌렀을 때 이벤트 (shift, alt, controll, capslock 등의 모든 키에 동작함)

 

onkeyup

- 키를 눌렀다가 뗐을 때 이벤트 (onkeydown에서 인식하는 키를 동일하게 인식)

 

onkeypress

- 실제로 글자가 써질 때 이벤트 (shift, tap, enter 등의 특수키는 인식 못함)

 

<html>
  <head>
      <title>키보드 이벤트</title>
    <script type="text/javascript" src="//code.jquery.com/jquery-1.11.1.min.js"></script>
  </head>
  <body>
      남은 글자수
      <h1>10</h1>
      <input type="text" maxlength="10" id="text">
  <script type="text/javascript">
    var inputChk = $("#text");
          inputChk.keyup(function () {	 
              if (this.value.length >= 10) {
                  $('h1').css('color','red');
              } else {
                  $('h1').css('color','blue');
              }
          });
  </script>
  </body>
</html>