DOM中两个元素之间的距离(以像素为单位)

Hom*_*ith 2 javascript dom

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

我正在考虑使用getBoundingClientRect,但是我看不到如何使用它来计算两个元素之间的距离。因此,例如,与的距离有多近。

Cam*_*kew 5

假设您有一个ID div1为的div和一个ID 为的div div2。您可以通过一些简单的数学计算从div1'中心到div2'中心的距离(以像素为单位)...

// 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);
Run Code Online (Sandbox Code Playgroud)

  • 这个答案使用的是jQuery ...但是如果您不想使用jQuery,则可以用`var div1rect = document.getElementById(“ div1”)。getBoundingClientRect();`... etc替换前两行。 (3认同)