2012-12-11 2 views
1

element.offset().left을 사용하면 부모로부터 요소의 오프셋 위치를 얻을 수 있습니다. 다른 요소에서 오프셋 위치를 가져 오는 방법이 있습니까? 예를 들어 여기 내 HTML은 다음과 같습니다.부모 이외의 요소로부터 오프셋을 가져 옵니까?

<div id="tile_id_579" class="product_tile"> 
<div class="selectContainer"> 
    <table style="width:100%;"> 
     <tbody> 
      <tr> 
       <td>   
       <div id="select-undefined" class="tzSelect"> 
        <div id="options-undefined" class="tzOptions" style="max-height: 500px; width: 250px; display: none; min-width: 118px;"> 
         <ul class="dropDown" id="dropdown-undefined"> 
          <li><div class="header">Hand-Tossed Style Pizza</div> 
           <div class="subheader">The crowd-pleasing pizza that everyone can agree on.</div> 
           <div class="optkey">0</div> 
          </li> 
          <li><div class="header">Pan Pizza</div> 
           <div class="subheader">Our Pan Pizza is America's favorite!</div> 
           <div class="optkey">1</div> 
          </li> 
         </ul> 
        </div> 
       </div> 
       </td> 
      </tr> 
     </tbody> 
    </table> 
</div> 
</div> 

데이터베이스에서 생성되었습니다. offset().left을 사용하면 #selecct-undefined div에서 오프셋을 얻을 수 있지만 #options-undefined div가 .selectContainer div와 얼마나 멀리 떨어져 있는지 알아야합니다. 이것이 가능한가? 문서에 관련하여 0하지만 왼쪽으로 공을되지 않습니다; 최고 : 381, 왼쪽

편집

는이 두 가지를 시도, 모두가 같은 일을 반환 추가하려면 그것은있을 수 없다.

var tip = $('#tile_id_579 #options-undefined .header'); 
tip.first().position(); 

var tip = $('#tile_id_579 #options-undefined .header'); 
tip.first().offset(); 

은 어떻게 왼쪽은 0입니다 가능성이 두 사업부이고이 때? 왼쪽 0은 브라우저 창 왼쪽에있는 것을 의미하지 않습니까?

enter image description here

+1

['.offset()'] (http://api.jquery.com/offset/)은 문서 ['.position()'] (http : //api.jquery .com/position /)은 오프셋 부모를 기준으로합니다. – j08691

+0

나는 둘 다 시도해 본 결과 둘 다 같은 값을 반환한다. 부모가 문서 자체가 아닐 때 이것이 가능한 방법을 잘 모르겠습니다 ... OP에 예제를 추가하십시오. – EmmyS

답변

0

당신의 요소는 당신이 .position() 대신 .offset를 사용할 수 지정된 그 부모 내에서 실제로이기 때문에(). 그러나 .selectContainer가 가장 가까운 상대 부모가 아닌 경우 요소와 해당 "기타"요소의 위치를 ​​가져와 차이를 계산해야합니다.

var myPos = $('#options-undefined').offset(); 
var otherPos = $('#options-undefined').closest('.selectContainer').offset();//if #options-undefined wasn't a child of .selectContainer you would do $('.selectContainer').offset(); 

var _offset = { 
    top: otherPos.top - myPos.top, 
    left: otherPos.left - myPos.left 
} 
관련 문제