最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get distance between two divs - Stack Overflow

programmeradmin3浏览0评论

So I have one div inside the other - how can I get distance between them?

I tried something like $('#child').parentsUntil($('#parent')).andSelf() - but it returns an object, not a distance.

P.S. I need it to push other buttons.

So I have one div inside the other - how can I get distance between them?

I tried something like $('#child').parentsUntil($('#parent')).andSelf() - but it returns an object, not a distance.

P.S. I need it to push other buttons.

Share Improve this question edited Oct 1, 2012 at 9:57 NoNameZ asked Oct 1, 2012 at 9:54 NoNameZNoNameZ 7955 gold badges14 silver badges22 bronze badges 1
  • Try to test with $("#child").position().left and if needed subtract $("#parent").position().left from this value. – VisioN Commented Oct 1, 2012 at 9:58
Add a ment  | 

4 Answers 4

Reset to default 5

http://api.jquery./position/

to get the left distance you can use:

var distLeft = $('#child').position().left; 

That will return the distance in px relative to the offset parent

if you're interested into the element's page offset than:

var offsLeft = $('#child').offset().left;

http://api.jquery./offset/

There's this awesome getBoundingClientRect function. Anything else is just a-b

https://developer.mozilla/en-US/docs/DOM/element.getBoundingClientRect

You can use offset

  var childOffset = $('#child').offset(), parentOffset = $('#child').parentsUntil($('#parent')).offset();
    var leftDistance  =childOffset.left - parentOffset.left;
    var topDistance = childOffset.top- parentOffset.top;

Did you try something like?

 $('innerDiv').position().left; 
发布评论

评论列表(0)

  1. 暂无评论