JAVA/Muzi
[Javascript] 요소의 크기와 뷰포트에 대한 위치를 반환 with 팝업창(popup)
미눅스[멘토]
2024. 8. 5. 18:28
728x90
const element = document.querySelector('#some-element'); // 요소를 선택
const rect = element.getBoundingClientRect(); // 요소의 위치와 크기 정보
console.log(rect.width); // 요소의 너비
console.log(rect.height); // 요소의 높이
console.log(rect.top); // 요소의 상단 경계로부터의 거리
console.log(rect.right); // 요소의 오른쪽 경계로부터의 거리
console.log(rect.bottom); // 요소의 하단 경계로부터의 거리
console.log(rect.left); // 요소의 왼쪽 경계로부터의 거리
getBoundingClientRect()메소드를 이용한
PopUp창 만들기 예제
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#minu {
border:1px solid black;
height:50px;
}
#popup {
position:absolute;
width:300px;
height:300px;
color:yellow;
background-color: black;
border: 1px solid block;
display: none;
}
</style>
</head>
<body>
<div id="popup">
<div class="merong">테</div>
<div class="merong">스</div>
<div class="merong">트</div>
</div>
<div id="minu" onclick="fclick()">미누마우스클릭</div>
<script>
const myPopup = document.querySelector("#popup");
const myMinu = document.querySelector("#minu");
let isShow = false;
function fclick(){
if(!isShow){
console.log("9999")
let left = myMinu.getBoundingClientRect().left;
let top = myMinu.getBoundingClientRect().top;
myPopup.style.left = (left) + "px";
myPopup.style.top= (top) + "px";
myPopup.style.display = "block";
}else {
console.log("8888")
myPopup.style.display = "none";
}
isShow = !isShow;
}
</script>
</body>
</html>