jQuery 使用jQuery查找两个DIV之间的距离?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15149573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:28:25  来源:igfitidea点击:

Find distance between two DIVs using jQuery?

javascriptjqueryhtml

提问by Ardi Madadi

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动态找到距离。

回答by threenplusone

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 并引用它。

回答by Dom

Use .offset():

使用.offset()

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

回答by bumsoverboard

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');
}