测量两个HTML元素中心之间的距离 [英] Measure distance between two HTML elements' centers

查看:1713
本文介绍了测量两个HTML元素中心之间的距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下HTML元素:

 < div id =x>< / div> 

< div id =ystyle =margin-left:100px;>< / div>

...如何使用JavaScript查找它们之间的像素距离?

解决方案

获取他们的位置,并使用毕达哥拉斯定理来确定他们之间的距离...

 (function(){

var getPositionAtCenter = function(element){
var data = element.getBoundingClientRect();
返回{
x:data.left + data.width / 2,
y:data.top + data.height / 2
};
};

var getDistanceBetweenElements = function(a,b){
var aPosition = getPositionAtCenter(a);
var bPosition = getPositionAtCenter(b);

返回Math.sqrt(
Math.pow(aPosition.x - bPosition.x,2)+
Math.pow(aPosition.y - bPosition.y,2)
);
};

var distance = getDistanceBetweenElements(document.getElementById(x),
的document.getElementById( Y));

})();

上(原点位于左上角),因此您可以想象一个右键菜单,

您可以修改方程以得到 c 的值, code>通过获得对方的平方根。



然后,您只需将值( x y 是元素之间的差异,一旦它们的中心被确定ned),你会发现斜边的长度,这是元素之间的距离。


If I have HTML elements as follows:

<div id="x"></div>

<div id="y" style="margin-left:100px;"></div>

...how do I find the distance between them in pixels using JavaScript?

解决方案

Get their positions, and use the Pythagorean Theorem to determine the distance between them...

(function() {

    var getPositionAtCenter = function (element) {
        var data = element.getBoundingClientRect();
        return {
            x: data.left + data.width / 2,
            y: data.top + data.height / 2
        };
    };

    var getDistanceBetweenElements = function(a, b) {
        var aPosition = getPositionAtCenter(a);
        var bPosition = getPositionAtCenter(b);

        return Math.sqrt(
            Math.pow(aPosition.x - bPosition.x, 2) + 
            Math.pow(aPosition.y - bPosition.y, 2) 
        );
    };

    var distance = getDistanceBetweenElements(document.getElementById("x"),
                                              document.getElementById("y"));

})();

jsFiddle.

The Pythagorean Theorem relates to the relationship between the sides of a right-angled triangle.

The elements are plotted on a Cartesian coordinate system (with origin in top left), so you can imagine a right-angled triangle between the elements' coordinates (the unknown side is the hypotenuse).

You can modify the equation to get the value of c by getting the square root of the other side.

Then, you simply plug the values in (the x and y are the differences between the elements once their centers are determined) and you will find the length of the hypotenuse, which is the distance between the elements.

这篇关于测量两个HTML元素中心之间的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆