web/jQuary

[jQuery]x축,y축 위치 알아내기-.offset().top과 .offset().left

바까 2020. 5. 26. 10:10
반응형

$("선택자").offset().left;

화면상에서 특정 요소의 x축 위치 알아내고자 할 때 사용한다.

$("선택자").offset().top;

화면상에서 특정 요소의 y축 위치 알아내고자 할 때 사용한다.


[html]

<div></div>

[css]

div{width: 200px; height: 200px; background-color: blue; margin: 100px;}

*margin을 모두 100px 줬다. 즉 화면상의 x,y축은 100px 인 것이다.

[js]

y축의 위치

$(document).ready(function(){
   alert($("div").offset().top);
});

x축의 위치

$(document).ready(function(){
   alert($("div").offset().left);
});

[결과화면]


객체의 x, y축은 왼쪽 위의 꼭지점이 기준이고,

.offset().bottom과 .offset().right으로 시도해봤지만 undefined라고 나온다. 

만약 오른쪽 위치와 아래의 위치를 알고싶다면

 alert($(window).width()-$("div").offset().left+ $("div").outerWidth());//offset().right
 
 alert($(window).height()-$("div").offset().top+ $("div").outerHeight());//offset().bottom

으로 사용하면 된다.

반응형