jquery确定2个div之间的重叠量

时间:2011-06-09 19:15:42

标签: javascript jquery intersection

我有两个相互重叠的div(矩形)。如何在javascript中确定两个div之间的交集/重叠量?

我意识到我会得到每个矩形的尺寸:
offset.top,offset.left,elt.offsetWidth,elt.offsetHeight

但是从那里我不确定如何确定重叠量。

1 个答案:

答案 0 :(得分:2)

var div1 = $('#div1');
var div2 = $('#div2');
var both = div1.add( div2 );

var leftMost = (div1.offset( ).left < div2.offset( ).left ? div1 : div2);
var rightMost = both.not( leftMost );
var topMost = (div1.offset( ).top < div2.offset( ).top ? div1 : div2);
var botMost = both.not( topMost );

var overlap = {   'x': (leftMost.offset( ).left + leftMost.outerWidth( )) - rightMost.offset( ).left,
                  'y': (topMost.offset( ).top + topMost.outerHeight( )) - botMost.offset( ).top };