특정 요소의 위치 값을 얻고 싶을 때 offset()과 position()을 사용한다.
offset은 브라우저를 기준으로, position은 포지셔닝 콘텍스트(<body>)를 기준으로 한다.
리턴 자료형은 객체(left, top 속성)이다.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>14_offset.html</title>
<script src="jquery-3.6.1.min.js"></script>
<style>
#box {
width:600px;
height:400px;
position: fixed;
left:50%;
top:50%;
margin:-200px 0 0 -300px;
background:#888;
}
#child {
width:200px;
height:200px;
position: relative;
left:200px;
top:100px;
background: #00bfff;
cursor: pointer;
box-shadow: 0 12px 15px 0 rgba(0, 0, 0, 0.24), 0 17px 50px 0 rgba(0, 0, 0, 0.19);
}
</style>
</head>
<body>
<h3>offset과 position</h3>
<div id="box">
<div id="child"></div>
</div>
<script>
$("#child").click(function(){
//alert("test");
let offset = $("#child").offset();
let position = $("#child").position();
// alert(offset);
// alert(position);
let msg = "";
msg += "offset left : " + offset.left + "<br>";
msg += "offset top : " + offset.top + "<br>";
msg += "position left : " + position.left + "<br>";
msg += "position top : " + position.top + "<br>";
$("#child").html(msg);
}); //click end
</script>
</body>
</html>
#child의 위치 값을 확인해보자.
#child에 position으로 relative를 주었는데 relative는 부모 영역이 기준이기 때문에 position의 값은 연두색 화살표 끝을 기준으로 한다. 따라서 position은 브라우저의 크기를 조절해도 값이 변하지 않고 일정하다.
offset은 앞서 말했듯이 브라우저를 기준으로 한다. 따라서 브라우저의 크기를 조절하면 값이 바뀐다.
'웹개발 교육 > jQuery' 카테고리의 다른 글
[44일] jQuery (16) - Ajax (0) | 2022.09.28 |
---|---|
[44일] jQuery (15) - 스크롤 이동 (0) | 2022.09.28 |
[43일] jQuery (13) - 아날로그 시계 (0) | 2022.09.27 |
[43일] jQuery (11) - moment (0) | 2022.09.27 |
[43일] jQuery (10) - addClass (0) | 2022.09.27 |