Day6_VSCODE_JavaScript_이벤트
2023. 4. 12. 19:40ㆍJavascript
🟡이벤트
웹 브라우저가 알려주는 HTML 요소에 대한 사건이 발생
웹 페이지에 사용된 자바스크립트는 발생한 이벤트에 반응하여 특정 동작을 수행할 수 있다.
🟢이벤트타입 - 발생한 이벤트의 종류를 나타내는 문자열로 이벤트 명이라고함
- 키보드,마우스,HTML DOM, Window 객체.. 등 처리하는 이벤트 제공
- https://developer.mozilla.org/ko/docs/Web/API/Event
🟢이벤트 타겟 - 이벤트가 일어날 객체를 의미
🟢이벤트리스너
- 이벤트가 발생했을 때 그 처리를 담당하는 함수
- 이벤트 핸들러라고 부름
- 지정된 타입의 이벤트가 특정 요소에서 발생하면 웹 브라우저는 그 요소에 등록된 이벤트 리스너를 실행
[예시] 이벤트 등록 객체.addEventListenr(이벤트타입,이벤트리스너) 이벤트 제거 객체.removeEventListenr(이벤트 타입, 이벤트 리스너)
🟢이벤트 객체
- 특정타입의 이벤트와 관련이 있는 객체
- 이벤트 객체는 해당 타입의 이벤트에 대한 상세 정보를 저장하고 있음
- 모든 이벤트 객체는 이벤트의 타입을 나타내는type 프로퍼티와 이벤트 대상을 나타내는 target 프로퍼티를 가지고 있음
- 이벤트 객체를 이벤트 리스너가 호출할 때 인수로 전달
function sendit(e){ e.target(button), e.type(click) } [HTML] <input type='button' onclick='sendit()' value='완료'>
🟢이벤트 전파(Event Propagation)
- 이벤트가 발생 했을 때 브라우저가 이벤트 리스너를 실행시킬 대상 요소를 결정하는 과정
- document 객체나 html 문서의 요소에서 이벤트가 발생하면 대상 요소를 결정하기 위해 이벤트 전파가 일어남
✔버블링 전파방식 - 자식에서 부모로 이벤트를 전파
✔캡처링 전파방식 - 부모에서 자식으로 이벤트를 전파
✔이벤트 전파를 막는 방법
이벤트객체명.stopPropagation()
예시) 버튼을 누르면 콘솔창에 target을 띄우기
<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">
<title>이벤트 객체1</title>
<script>
window.onload = function() {
const btn = document.getElementById('btn')
btn.addEventListener('click',clickBtn);
}
function clickBtn(e){
console.log(e.target) //<button type="button" id="btn">
console.log(e.target.id) //btn
console.log(e.target.value)
console.log(e.target.type)
}
</script>
</head>
<body>
<h2>이벤트 객체 1</h2>
<button type="button" id="btn" value="확인">123</button>
</body>
주의사항
e.target = <button type="button" id="btn" value="확인">123</button>
e.target.id = btn
e.target.type = button
e.target.value = 확인 !
내가 해본 예시 : 마우스 커서를 가져다대면 색깔변경
<body onload="init()">
<p onmouseover="this.style.backgroundColor ='orchid'"
onmouseout="this.style.backgroundColor='white'">html로 작성</p>
<p id="p">이건 자바스크립트 이벤트</p>
<script>
function init(){
const p = document.getElementById('p')
p.onmouseover = over;
p.onmouseout = out;
}
function over(){
p.style.backgroundColor='gold'
}
function out(){
p.style.backgroundColor='white'
}
</script>
</body>
728x90
'Javascript' 카테고리의 다른 글
✔️ iframe 페이지 전체 새로고침 (0) | 2023.10.27 |
---|---|
Day6_VSCODE_JavaScript_이터레이터+이터러블 (1) | 2023.04.12 |
Day5_VSCODE_JavaScript_Wrapper 객체 (0) | 2023.04.11 |
Day5_VSCODE_JavaScript_ (재정리) _상속의 활용 (0) | 2023.04.11 |
Day5_VSCODE_JavaScript_ (재정리) _클래스 심화 (0) | 2023.04.11 |