본문 바로가기
괴발개발/js

자바스크립트 js 이벤트

by 맛길만걷자 2024. 6. 14.
728x90
반응형
//인라인 이벤트 모델 확인하기
function test1(button){
   // console.log(button)

   button.style.backgroundColor="red";
   button.style.color= "white";
}

//고전 이벤트 모델 확인하기
console.log(document.getElementById("test2-1"));

document.getElementById("test2-1").onclick = function(){
    //익명 함수(이벤트 핸들러에 많이 사용함)
    alert("고전 이벤트 모델 확인");
}

//이벤트 제거
document.getElementById("test2-2").onclick = function(){

    //test2-1 이벤트 제거
    document.getElementById("test2-1").onclick = null;
    alert("test2-1 이벤트 제거");
}

// 고전 이벤트 모델 단점
// -> 한 요소에 동일한 이벤트 리스너(onclick)에 대한
//    다 수의 이벤트 핸들러(배경색 변경, 폰트크기 변경)를 작성할 수 없다.
//    (마지막으로 해석된 이벤트 핸들러만 적용됨)
document.getElementById("test2-3").onclick=function(event){
   
    //버튼색 바꾸기
    // 방법 1) 요소를 문서에서 찾아서 선택
    // document.getElementById("test2-3").style.backgroundColor="green";

    // 방법 2) 매개변수 e 또는 event 활용하기
    // -> 이벤트 핸들러에 e 또는 event를 작성하는 경우
    //    해당 이벤트와 관련된 모든 정보가 담긴 이벤트 객체가 반환됨

    // event.target : 이벤트가 발생한 요소
    //console.log(event);

    // event.target.style.backgroundColor ="yellow";

    // 방법 3) this 활용하기 -> 이벤트가 발생한 요소 (event.target과 동일)
    //console.log(this);
    this.style.backgroundColor="yellow";

}

/* document.getElementById("test2-3").onclick =function(){
    document.getElementById("test2-3").style.fontSize="50px";
} */



// 표준 이벤트 모델
document.getElementById("test3").addEventListener("click", function(){

    //this : 이벤트가 발생한 요소
    // console.log(this.clientWidth); //해당요소의 너비(테두리 제외)
    // console.log(this.offsetWidth); //해당요소의 너비(테두리 포함)

    //this.style.width = "300px"; //현재 요소 너비 변경
   
    this.style.width = this.clientWidth + 20 +"px";

});

// test3에 이미 click 이벤트에 대한 동작이 존재
// 중복으로 적용
document.getElementById("test3").addEventListener("click", function(){
    this.style.height = this.clientHeight+ 20 +"px";
})

// 연습문제
// document.getElementById("changeBtn1").addEventListener("click", function() {
//     const div1 = document.getElementById("div1");
//     const input1 = document.getElementById("input1").value;

    /*
    // input1에 작성된 값 얻어오기
    const bgColor =input1.value;
    */

//     //div1 배경색 변경
//     div1.style.backgroundColor = input1;


// });

//input1에 값이 변경되었을 떄 입력된 값으로 배경색 변경
document.getElementById("input1").addEventListener("change",function(){

    //change 이벤트
    // - text관련 input태그는
    // 입력된 값이 변할 때는 change라고 하지 않고
    // 입력이 완료된 후 포커스를 잃거나, 엔터를 입력하는 경우
    // 입력된 값이 이전과 다를 경우 change 이벤트가 발생한걸로 인식한다.
    console.log("change 이벤트 발생");

    const div1 = document.getElementById("div1");

    //input1에 작성된 값 얻어오기
    const bgColor = this.value;

    div1.style.backgroundColor = bgColor;

})
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>06_이벤트</title>
    <style>
        #test3{
            width:200px;
            height: 200px;
            border:1px solid black;
            background-color: pink;
            cursor: pointer;
        }

        /* 연습문제 */
        #div1{
            width:200px;
            height: 200px;
            border:1px solid black;

        }
    </style>
</head>
<body>

    <h1>이벤트(event)</h1>

    <pre>
        이벤트(Event): 동작,행위
        -> 브라우저에서의 동작, 행위 : click, keydown, keyup, mouseover, drag, change, submit ...

        이벤트 리스너(Event Listner)
        -> 이벤트가 발생하는 것을 대기하고 있다가
           이벤트가 발생하는 것이 감지되면 연결된 기능(함수)을 수행하는 것

           ex) onclick, onkeyup, onchange, onsubmit ... (on 이벤트)

           onclick = "함수명()"

        이벤트 핸들러(Event Handler)
          -> 이벤트 리스너에 연결된 기능으로
             이벤트 발생 시 수행하고자 하는 내용을 작성해둔 함수(function)
    </pre>
   
    <hr>

    <h3>인라인 이벤트 모델</h3>
    <pre>
        요소 내부에 이벤트를 작성하는 방법으로
        on이벤트명 = "함수명()" 형태로 작성

    </pre>

    <button onclick="test1(this)">인라인 이벤트 모델 확인</button>



    <hr>

    <h3>고전 이벤트 모델</h3>
    <pre>
        요소가 가지고 있는 이벤트 속성(이벤트 리스너)에
        이벤트 핸들러를 연결하는 방법으로

        인라인 모델처럼 HTML 요소에  JS 코드가 포함되는 것이 아닌
        script에만 이벤트 관련 코드를 작성할 수 있다.
    </pre>

    <button id="test2-1">고전 이벤트 모델 확인</button>
    <button id="test2-2">test2-1 이벤트 제거</button>
    <button id="test2-3">고전 이벤트 모델 단점</button>

    <hr>

    <h3>표준 이벤트 모델</h3>
    <pre>
        - W3C (HTML, CSS, JS 웹표준 재정 단체)
          공식적으로 지정한 이벤트 모델(이벤트 동작 지정 방법)

        - 한 요소에 여러 이벤트 핸들러를 설정할 수 있다.
            -> 고전 이벤트 모델 단점 보완
    </pre>
    <hr>

    <div id="test3">클릭하면 크기 늘나게!</div>

    <!--
        *JS 코드를 body태그 마지막에 작성하는 이유 *
        1. 고전/표준 이벤트 모델 방식의 코드 수행을 위해
           (HTML 요소 먼저 랜더링 -> JS코드 해석)
       
        2. head에 용량이 큰 JS를 추가하면
           페이지 로딩 시간(흰 화면)이 길어지게 된다.

           -> body태그 마지막으로 옮기면
              일단 화면부터 렌더링 후 JS코드를 나중에 해석
    -->

    <hr>

    <h3>이벤트 연습문제</h3>

    색상을 영어로 입력한 후 변경 버튼을 클릭하면 #div1의 배경색이 변경되도록 하시오

    <div id="div1"></div>
    <input type="text" id="input1">
    <button id="changeBtn1">변경</button>

    <script src="js/06_이벤트.js"> </script>

</body>
</html>
728x90
반응형

'괴발개발 > js' 카테고리의 다른 글

문자열 숫자형 변환  (0) 2024.06.18
정규표현식  (0) 2024.06.17
요소 접근 방법  (0) 2024.06.13
데이터 입출력  (0) 2024.06.13
javascript 개요  (1) 2024.06.12