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让我得到了 div 的偏移量#selecct-undefined,但我需要得到 div 离#options-undefineddiv 的距离.selectContainer。这可能吗?

编辑添加

尝试了这两种方法,并且都返回相同的内容:顶部:381,左侧:0。但是相对于文档,左侧不是 0;不可能。

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

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

当这是 div 所在的位置时,left 怎么可能是 0?0 left 不是意味着它一直在浏览器窗口的左侧吗?

在此处输入图像描述

4

1 回答 1

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
}
于 2012-12-11T18:09:29.390 回答