jQuery 이벤트 공부햇다

binary·2021년 12월 24일
2

일팔공

목록 보기
10/20
post-thumbnail

이벤트

이벤트 사용하는 방법

$(document).ready(function() {
  $(selector).이벤트메소드(function (event) { ... });
});

이벤트 메소드 모음

click 이벤트

<!-- jquery include -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>

<script>
$(document).ready(function () { 
  $("h1").click(function () {
    alert("클릭");
  });
});
</script>
<h3>이벤트 연결</h3>
<hr>
<h1>click</h1>

| 실행화면

hover() 이벤트

mouseenter 이벤트와 mouseleave 이벤트를 동시 연결하여 사용해야 한다.

<!-- jquery include -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>

<script>
$(document).ready(function () { 
  $("h2").hover(
    function () {
      $(this).css({
        backgroundColor: "pink",
        color: "purple",
      });
    },
    function () {
      $(this).css({
        backgroundColor: "",
        color: "",
      });
    }
  );
});
</script>
<h3>이벤트 연결</h3>
<hr>
<h2>hover</h2>

| 실행화면

글자 위에 마우스 커서를 올리면 "pink"로 바뀌고, 내리면 원래의 기본 색으로 돌아온다.

이벤트 연결 메소드 on()

on() 메소드로 이벤트를 연결할 수 있다.

1. 첫 번째 방법 : 이벤트를 문자열로 연결한다.

<!-- jquery include -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>

<script>
  $(document).ready(function(){
    $("#box").css({
      width:100,
      height:100,
      backgroundColor:"orange",
    }).on("click",function(){
      $(this).css({
        backgroundColor:"purple",
      })
    }).on("mouseenter", function(){
      $(this).css({
        backgroundColor:"yellow",
      })
    }).on("mouseleave", function(){
      $(this).css({
        backgroundColor:"red",
      })
    })
  })
</script>
<h3>이벤트</h3>
<hr>
<div id="box"></div>

2. 두 번째 방법 : 이벤트를 키값으로 연결한다.

<!-- jquery include -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>

<script>
  $(document).ready(function () {
    $("#box")
      .css({
        width: 200,
        height: 200,
        backgroundColor: "yellow",
      })
      .on({
        click: function () {
          $(this).css({
            backgroundColor: "pink",
          });
        },
        mouseenter: function () {
          $(this).css({
            backgroundColor: "purple",
          });
        },
        mouseleave: function () {
          $(this).css({
            backgroundColor: "yellow",
          });
        },
      });
    });
</script>
<h3>이벤트</h3>
<hr />
<div id="box"></div>

| 실행화면

  • box의 원래 생김새 #box

  • box에 마우스를 올렸을 때 .on (mouseenter)

  • box를 클릭했을 때 .on (click)

  • box에서 마우스가 떠났을 때 .on (mouseleave)

++ off() 메소드는 이벤트를 제거할 수 있다.

기본 이벤트 제거

event.preventDefault()

제거하고 싶은 이벤트에 위 코드를 작성하면 기본 이벤트가 제거된다. 해당하는 그 이벤트만! 제거된다.


0개의 댓글