使用jQuery找到两个div之间的距离?

时间:2023-01-13 15:24:25

I have two DIVs that I need to know the calculated browser distance (in height) of them. I have read about the offset feature but the examples were not written for the way I am trying to do this.

我有两个div,我需要知道它们的浏览器距离(以高度计算)。我读过有关偏移特性的文章,但是这些例子并不是为我这样做而编写的。

Example usage:

使用示例:

<div class="foo"></div>
<div class="bar"></div>

I want to know the distance between these two.

我想知道这两者之间的距离。

Please help me to find the distance dynamically with jQuery.

请帮助我用jQuery动态查找距离。

3 个解决方案

#1


56  

Something like this should work:

像这样的东西应该是有用的:

$('.foo').offset().top - $('.bar').offset().top

As long as each class only has one element on the page.
If they are not unique, give the two elements an ID and reference with that.

只要每个类在页面上只有一个元素。如果它们不是唯一的,那么给这两个元素一个ID和引用。

#2


9  

Use .offset():

使用.offset():

$('.foo').offset().top - $('.bar').offset().top

#3


0  

This function finds the distance in pixels between the centre of two elements, no jquery:

此函数查找两个元素中心之间的距离(以像素为单位),没有jquery:

function distanceBetweenElems(elem1, elem2) {
    var e1Rect = elem1.getBoundingClientRect();
    var e2Rect = elem2.getBoundingClientRect();
    var dx = (e1Rect.left+(e1Rect.right-e1Rect.left)/2) - (e2Rect.left+(e2Rect.right-e2Rect.left)/2);
    var dy = (e1Rect.top+(e1Rect.bottom-e1Rect.top)/2) - (e2Rect.top+(e2Rect.bottom-e2Rect.top)/2);
    var dist = Math.sqrt(dx * dx + dy * dy);
    return dist;
}

I use it like this:

我这样使用它:

var target1 = document.querySelector('#foo');
var target2 = document.querySelector('#bar');
if (distanceBetweenElems(target1,target2)<100){
     target1.classList.add('active');
}

#1


56  

Something like this should work:

像这样的东西应该是有用的:

$('.foo').offset().top - $('.bar').offset().top

As long as each class only has one element on the page.
If they are not unique, give the two elements an ID and reference with that.

只要每个类在页面上只有一个元素。如果它们不是唯一的,那么给这两个元素一个ID和引用。

#2


9  

Use .offset():

使用.offset():

$('.foo').offset().top - $('.bar').offset().top

#3


0  

This function finds the distance in pixels between the centre of two elements, no jquery:

此函数查找两个元素中心之间的距离(以像素为单位),没有jquery:

function distanceBetweenElems(elem1, elem2) {
    var e1Rect = elem1.getBoundingClientRect();
    var e2Rect = elem2.getBoundingClientRect();
    var dx = (e1Rect.left+(e1Rect.right-e1Rect.left)/2) - (e2Rect.left+(e2Rect.right-e2Rect.left)/2);
    var dy = (e1Rect.top+(e1Rect.bottom-e1Rect.top)/2) - (e2Rect.top+(e2Rect.bottom-e2Rect.top)/2);
    var dist = Math.sqrt(dx * dx + dy * dy);
    return dist;
}

I use it like this:

我这样使用它:

var target1 = document.querySelector('#foo');
var target2 = document.querySelector('#bar');
if (distanceBetweenElems(target1,target2)<100){
     target1.classList.add('active');
}