How to get offset() relative to parent in jQuery?

前端 未结 4 849
无人共我
无人共我 2020-12-25 09:37

This gives me the position of some element from the left edge of the main window:

$(\'#bar\').offset().left;

If that element is situated in

相关标签:
4条回答
  • 2020-12-25 10:09

    Position within a div relative to its parent:

    In my case, when scroll changed the calculated offset also changed and it shouldn't so i ended up using pure javascript which is quicker anyway...

    element.get(0).offsetTop

    Other variation like Left is also possible element.get(0).offsetLeft

    Conclusion

    element.offset().top or position() are not optimal for position relative cases.

    0 讨论(0)
  • 2020-12-25 10:16

    Use the position() method.

    $('#bar').position().left;
    
    0 讨论(0)
  • 2020-12-25 10:25
    offsetLeft = $('#bar').position().left;
    offsetTop = $('#bar').position().top;
    
    0 讨论(0)
  • 2020-12-25 10:31

    It's simple enough: get the offset of the element and substract the offset of its parent.

    var elem = $("#bar");
    var offset = elem.offset().left - elem.parent().offset().left;
    
    0 讨论(0)
提交回复
热议问题