getBoundingClientRect();를 이용해서 클릭한 태그의 위치 가져오기
Element.getBoundingClientRect()메서드는 DOMRect요소의 크기와 뷰포트에 상대적인 위치에 대한 정보를 제공 하는 객체를 반환
<!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>Coordinates</title>
<style>
div {
width: 300px;
height: 300px;
background-color: teal;
margin: 10px;
}
.special {
background-color: tomato;
}
</style>
</head>
<body>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div class="special"></div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<script>
const special = document.querySelector('.special');
function getCoordinates(event) {
const rect = special.getBoundingClientRect();
console.log(rect);
console.log(`client: ${event.clientX}, ${event.clientY}`);
console.log(`page: ${event.pageX}, ${event.pageY}`);
}
special.addEventListener("click", (event) => {
getCoordinates(event);
});
</script>
</body>
</html>
'웹 개발 > 바닐라js' 카테고리의 다른 글
[따라만들기] modal popup (0) | 2022.02.20 |
---|---|
[따라만들기] carouse slider (0) | 2022.02.20 |
[드림코딩] 윈도우 사이즈 가져오기 (0) | 2021.09.21 |
[노마드코더] 바닐라JS 챌린지 - 랜덤 그라데이션 백그라운드 (0) | 2021.09.02 |
[노마드코더] 바닐라JS 챌린지 - 크리스마스 이브 D-day 계산기 (0) | 2021.09.02 |
[드림코딩] 클릭 후 좌표 가져오기