2010-11-24 78 views
2

我試圖使用jQueryjQuery UI<ul>元素水平位於<div>內部。jQuery:相對於另一個元素的元素偏移量()座標

我想獲得位於<li>元素中居中他們裏面#the_parent按鈕的座標,但我得到的每一次變化的位置我調整瀏覽器窗口,我怎麼能得到相對#the_parent的位置?

<script type:"text/javascript"> 
    $(document).ready (function() { 
     $(".button").click (function() { 
      var offset = $(this).offset(); 
      alert (offset.left); 
     }); 
    }); 
</script> 
<style type="text/css"> 
    #dragme li { float:left; list-style:none; } 
    #the_parent { width:100%; } 
    .spacer { width:100px; } 
    .button div { padding:5px; background-color:darkgrey; color:white; } 
</style> 
<!-- this is contained inside another div of width:600px and it's centered in the middle of the page --> 
<div id="the_parent"> 
    <ul id="dragme"> 
     <li class="spacer"></li> 
     <li id="btn_01" class="button"> 
      <div>click</div> 
     </li> 
     <li class="spacer"></li> 
     <li id="btn_02" class="button"> 
      <div>click</div> 
     </li> 
     <li class="spacer"></li> 
    </ul> 
</div> 

回答

7

看起來像你想position(),而不是offset()。從jQuery文檔:

offset():獲取匹配元素集合中第一個元素相對於文檔的當前座標。

position():獲取匹配元素集合中第一個元素相對於偏移父元素的當前座標。

+0

謝謝,有時候我應該花幾分鐘的時間去看文檔 – vitto 2010-11-24 18:29:00

相關問題