jQuery
[Dseok의 코딩스터디] javascript & jquery .offset() 한방에 끝내기 | 요소 위치 계산 & 실전 활용법
Dseok
2025. 2. 20. 09:51
반응형
SMALL
📌 .offset()이란?
jQuery.offset() 메서드는 HTML 요소의 문서(document) 기준 위치를 가져오거나 설정하는 기능을 합니다. 주로 스크롤 애니메이션, 고정 위치 UI, 드래그 앤 드롭 기능 등 다양한 곳에서 활용됩니다.
✅ 기본 문법
$(selector).offset(); // 요소의 위치를 가져오기
$(selector).offset({ top: value, left: value }); // 요소의 위치 설정
- $(selector).offset() : 선택한 요소의 top(Y 좌표)과 left(X 좌표) 값을 반환합니다.
- $(selector).offset({ top: value, left: value }) : 요소를 원하는 위치로 이동시킵니다.
📌 .offset() 활용 예제 7가지
1️⃣ 요소의 현재 위치 가져오기
$(document).ready(function() {
let position = $("#box").offset();
console.log("Top: " + position.top + ", Left: " + position.left);
});
✅ 설명: #box 요소의 현재 top과 left 값을 콘솔에 출력합니다.
2️⃣ 버튼 클릭 시 특정 위치로 이동
$("#moveButton").on("click", function() {
$("#box").offset({ top: 200, left: 300 });
});
✅ 설명: #moveButton 클릭 시 #box 요소가 (200, 300) 위치로 이동합니다.
3️⃣ 마우스 클릭 위치에 요소 이동
$(document).on("click", function(event) {
$("#box").offset({ top: event.pageY, left: event.pageX });
});
✅ 설명: 사용자가 클릭한 위치로 #box 요소가 이동합니다.
4️⃣ 특정 요소 간 거리 계산
$(document).ready(function() {
let box1 = $("#box1").offset();
let box2 = $("#box2").offset();
let distance = Math.sqrt(Math.pow(box2.left - box1.left, 2) + Math.pow(box2.top - box1.top, 2));
console.log("두 요소 간 거리: " + distance + "px");
});
✅ 설명: #box1과 #box2 간의 거리를 계산하여 콘솔에 출력합니다.
5️⃣ 특정 요소가 화면에 보이는지 확인
$(window).on("scroll", function() {
let position = $("#target").offset().top;
let scrollTop = $(window).scrollTop();
let windowHeight = $(window).height();
if (position < scrollTop + windowHeight && position > scrollTop) {
console.log("요소가 화면에 보입니다!");
}
});
✅ 설명: 스크롤할 때 #target 요소가 화면에 보이는지 체크합니다.
6️⃣ 요소의 위치를 고정된 헤더 높이만큼 조정
$(document).ready(function() {
let headerHeight = $("#header").outerHeight();
$("#content").offset({ top: headerHeight + 20 });
});
✅ 설명: #content 요소가 #header 아래로 20px 떨어지도록 위치 조정합니다.
7️⃣ 특정 요소를 중앙 정렬하기
$(document).ready(function() {
function centerElement() {
let windowWidth = $(window).width();
let windowHeight = $(window).height();
let boxWidth = $("#box").outerWidth();
let boxHeight = $("#box").outerHeight();
$("#box").offset({
top: (windowHeight - boxHeight) / 2,
left: (windowWidth - boxWidth) / 2
});
}
centerElement();
$(window).resize(centerElement);
});
✅ 설명: #box 요소가 화면 중앙에 위치하도록 조정합니다. 창 크기가 변경될 때도 중앙 정렬됩니다.

📌 마무리 🎯
- .offset()은 요소의 위치를 가져오거나 설정할 때 사용됩니다.
- offset()을 활용하면 스크롤 애니메이션, 위치 조정, 드래그 앤 드롭 등의 다양한 기능을 구현할 수 있습니다.
- 클릭한 위치로 이동, 중앙 정렬, 요소 간 거리 계산, 화면 내 표시 여부 확인 등 실용적인 예제들을 직접 활용해 보세요!
🚀 이제 .offset()을 활용해 원하는 요소를 원하는 위치로 조정해 보세요!
반응형
LIST