如何获取 DOM 中两个元素之间的距离?
我正在考虑使用获取边界客户端矩形 https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect,但我不知道如何使用它来计算两个元素之间的距离。例如,a 与 an 有多接近。
假设你有一个带有 id 的 divdiv1
和一个带有 id 的 divdiv2
。您可以计算距离(以像素为单位)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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)