스퐁지송 개발노트

자바스크립트(버블링) 본문

JAVA_Script

자바스크립트(버블링)

강준석 2022. 12. 27. 18:11
728x90

버블링

한태그에서 이벤트 발생 

=> 그 태그에 이벤트가 실행

=> 부모로 넘어가서 또 이벤트가 작동

=> 부모가 또 있으면 또 넘어가서 작동

=> 부모가 없을때 까지 반복

 

예제)

 

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>

 <!-- 버블링이란

한태그에서 이벤트 발생 

=> 그 태그에 이벤트가 실행

=> 부모로 넘어가서 또 이벤트가 작동

=> 부모가 또 있으면 또 넘어가서 작동

=> 부모가 없을때 까지 반복 -->

    <!-- <form onclick="alert('form')">form
    <div onclick="alert('div')">div
        <p onclick="alert('p')">p
        </p>
    </div>
    </form> -->

    
    <!-- <form id="form">form
    <div>div
        <p>p
        </p>
    </div>
    </form> -->

    <div onclick="alert('내용아무거나')">
    <p onclick="event.stopPropagation()">p태그임</p>
    </div>



 <!-- jQuery -->
 <script src="https://code.jquery.com/jquery-3.6.2.min.js" integrity="sha256-2krYZKh//PcchRtd+H+VyyQoZ/e3EcrkxhM8ycwASPA=" crossorigin="anonymous"></script>
 <!-- JS -->
 <script src="script.js"></script>
</body>
</html>

 

css

*{
    border: 1px solid black;
    margin: 10px;

}

form{
    background: green;
    position: relative;
    width: 150px;
    height: 150px;
}

div{
    background: skyblue;
    position: absolute;
    top: 25px;
    left: 25px;
    width: 100px;
    height: 100px;
}

p{
    background: pink;
    position: absolute;
    top: 25px;
    left: 25px;
    width: 50px;
    height: 50px;
}

 

js

form.onclick = function(event){

    event.target.style.backgroundColor = 'yellow';

    console.log(event.target.tagName);
    //클릭한 주체(대상)가 출력
    console.log(this.tagName);
    // 코드 자체인 form을 출력

};

document.querySelector('p').addEventListener('click',function(e){
//뭔가 작동될거 해주기
alert('asdasdasd');
e.stopPropagation();
});

 

728x90
Comments