js+jq
by qwerew0
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<div id="wrap">
<h1>이벤트 연습</h1>
<p id="textZone">웹 브라우저에서 버튼을 클릭한다거나 mouse를 움직이거나 하는 모든 행위를 ‘이벤트’라고 합니다. 그리고 이벤트발생 시 함수의 실행문이 수행되도록 이벤트를 지정하는 것을 이벤트 핸들러라고 합니다.
</p>
<h2>click 메서드</h2>
<p><button id="btn1">click</button> </p>
<h2>mouseover 메서드</h2>
<p><button id="btn2" tabindex="1">mouseover</button> </p>
<h2>bind 메서드</h2>
<p><button id="btn3">bind</button> </p>
<h2>mouseleave 메서드</h2>
<div id="listWrap">
<h3>관련 사이트</h3>
<ul class="list1">
<li><a href="#">list1</a></li>
<li><a href="#">list2</a></li>
<li><a href="#">list3</a></li>
<li><a href="#">list3</a></li>
</ul>
</div>
<h2>hover 메서드</h2>
<h3><a href="#" class="hover">hover</a></h3>
</div>
CSS
* { margin:0; padding:0; } li{ list-style-type:none; }
body { font:12px/1.5 "굴림",Gulim; margin:10px; }
h2{margin-top:30px;}
a{color:#333;}
#textZone{width:700px;}
#listWrap{background:#cfcfcf;width:110px;padding:10px;}
.list1{display:none;}
JavaScript
const textZone = document.querySelector('#textZone');
//1. id="btn1" 클릭 했을때 id="textZone" 글자 색상을 파란색으로 변경
const btn1 = document.querySelector('#btn1');
btn1.onclick = function () {
textZone.style.color = 'blue';
};
//2. id="btn2"에 마우스 오버 했을때 id="textZone" 배경 색상을 노란색으로 변경
const btn2 = document.querySelector('#btn2');
btn2.onmouseover = function () {
textZone.style.backgroundColor = 'yellow';
};
//3. id="btn2"에 포커스가 생겼을때 id="textZone" 배경 색상을 노란색으로 변경
//키보드 tab키가 #btn2에 머물때 노란색으로 변경
btn2.onfocus = function () {
textZone.style.backgroundColor = 'yellow';
};
/*4. 두개이상의 이벤트(mouseover,click,focus)를 등록시킬때 */
const btn3 = document.querySelector('#btn3');
function textZone4() {
textZone.style.color = 'green';
textZone.style.fontWeight = 'bold';
}
btn3.addEventListener('mouseover', textZone4);
btn3.addEventListener('focus', textZone4);
btn3.addEventListener('click', function(){alert()});
btn3.addEventListener('click', function(){textZone.style.marginLeft="80px";}
);
/* property listener 로 이벤트 등록시 같은 이벤트 덮어씌워짐
btn3.onmouseover=textZone4;
btn3.onfocus=textZone4;
btn3.onclick=function(){alert()};
btn3.onclick=function(){textZone.style.marginLeft="80px";}
*/
//5. id="listWrap"에 마우스가 올라가 있으면 class="list1" 을 블록요소 변경합니다. mouseover와 비슷
const listWrap = document.querySelector('#listWrap');
const list1 = document.querySelector('.list1');
listWrap.onmouseenter = function () {
list1.style.display = 'block';
};
//6. id="listWrap"에서 마우스가 벗어나면 class="list1" 을 블록요소 변경합니다. mouseout과 비슷
listWrap.onmouseleave = function () {
list1.style.display = 'none';
};
//8. class="hover"인 요소에 마우스를 올렸을땐 함수1을 벗어났을때에는 함수2를 실행 합니다.
let hover = document.querySelector('.hover');
hover.addEventListener('mouseover', function () {
this.style.color = 'aqua'; //함수1
});
hover.addEventListener('mouseout', function () {
this.style.color = 'red'; //함수2
});