DOM中两个元素之间的距离(以px为单位) [英] Distance (in px) between two elements in the DOM

查看:155
本文介绍了DOM中两个元素之间的距离(以px为单位)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取DOM中的两个元素之间的距离?

How can I get the distance between two elements in the DOM?

我正在考虑使用 getBoundingClientRect ,但是我无法看到我如何使用它来计算两个元素之间的距离。所以,例如,一个来自一个。

I am thinking on using getBoundingClientRect, but I fail to see how can I use that in order to calculate the distance between two elements. So, for example, how close is a from an .

推荐答案

假装你有一个id为$ code> div1 和一个id为$ code> div2 的div。您可以使用一些简单的数学计算从 div1 的中心到 div2 的中心的距离(以像素为单位)。 ..

Pretend you have a div with id div1 and a div with id div2. You could calculate the distance (in pixels) from div1's center to div2's center with some simple math...

// get the bounding rectangles
var div1rect = $("#div1")[0].getBoundingClientRect();
var div2rect = $("#div2")[0].getBoundingClientRect();

// get div1's center point
var div1x = div1rect.left + div1rect.width/2;
var div1y = div1rect.top + div1rect.height/2;

// get div2's center point
var div2x = div2rect.left + div2rect.width/2;
var div2y = div2rect.top + div2rect.height/2;

// calculate the distance using the Pythagorean Theorem (a^2 + b^2 = c^2)
var distanceSquared = Math.pow(div1x - div2x, 2) + Math.pow(div1y - div2y, 2);
var distance = Math.sqrt(distanceSquared);

这篇关于DOM中两个元素之间的距离(以px为单位)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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