Stack/JavaScript
[JS] 이벤트
7ingout
2022. 4. 27. 15:40
자바스크립트 기초구문
산술연산자, 논리연산자, 비교연산자, 조건문
자바스크립트 DOM
이벤트
onclick 클릭이벤트
onmouseenter 마우스를 올렸을 때
onmouseleave 마우스가 떠났을 때
onmousemove 마우스가 움직일 때
resize 창의 크기가 조절될 때
1. html 요소 태그안의 속성
<button onclick="myFunc()">
2. 이벤트 리스너
addEventListener() 메서드를 사용
document.querySelector('button').addEventListener("이벤트", myFunc);
document.querySelector('button').addEventListener("이벤트", function(){alert("aaa")};)
18event.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">
<title>Document</title>
<style>
div {
width: 500px;
height: 500px;
background: pink;
}
#a {
width: 50px;
height: 50px;
background: tomato;
position: absolute;
top: 0;
left: 0;
border-radius: 50%;
/* transition: 0.1s; */
}
</style>
</head>
<body>
<button id="btn">클릭하세요</button>
<div id="box"></div>
<div id="a"></div>
<script>
// document.querySelector('#btn').onclick = eventOn; == 위에 버튼 옆에 onclick="eventOn()" 적는거랑 같음
document.querySelector('#btn').addEventListener('mouseenter', eventOn);
document.querySelector('#box').addEventListener('mousemove',function(e){
document.querySelector('#a').style.left=`${e.pageX}px`;
document.querySelector('#a').style.top=`${e.pageY}px`;
console.log(`x좌표는 ${e.pageX}이고, y좌표는 ${e.pageY}이다.`);
});
function eventOn(){
console.log('이벤트가 발생했습니다.');
}
window.addEventListener('resize',function(e){
console.log(e);
// console.log(e.target.innerWidth);
// console.log(e.target.innerHeight);
let wwid = window.innerWidth;
let whei = window.innerHeight;
document.querySelector('#box').style.width=`${wwid}px`;
document.querySelector('#box').style.height=`${whei}px`;
})
</script>
</body>
</html>