如果我有以下HTML元素:
<div id="x"></div>
<div id="y" style="margin-left:100px;"></div>
如何使用JavaScript找到它们之间的像素距离?
如果我有以下HTML元素:
<div id="x"></div>
<div id="y" style="margin-left:100px;"></div>
如何使用JavaScript找到它们之间的像素距离?
function getPositionAtCenter(element) {
const {top, left, width, height} = element.getBoundingClientRect();
return {
x: left + width / 2,
y: top + height / 2
};
}
function getDistanceBetweenElements(a, b) {
const aPosition = getPositionAtCenter(a);
const bPosition = getPositionAtCenter(b);
return Math.hypot(aPosition.x - bPosition.x, aPosition.y - bPosition.y);
}
const distance = getDistanceBetweenElements(
document.getElementById("x"),
document.getElementById("y")
);
Math.hypot()
,您可以使用以下内容代替:Math.sqrt(
Math.pow(aPosition.x - bPosition.x, 2) +
Math.pow(aPosition.y - bPosition.y, 2)
);
这些元素被绘制在笛卡尔坐标系上(原点在左上角),所以你可以想象元素坐标之间形成了一个直角三角形(未知边为斜边)。
你可以修改方程式,通过对另一边进行平方根运算来获取c
的值。
然后,你只需将数值插入其中(x
和 y
是元素中心确定后的差值),就可以找到斜边的长度,即两个元素之间的距离。
就目前而言,由于div现在是空的,基本思路是测量它们左上角之间的距离。
distX = y.offsetLeft - x.offsetLeft;
distY = y.offsetTop - x.offsetTop;
distance = Math.sqrt(distX*distX + distY*distY);
alert(Math.floor(distance));
但是如果您在
无论如何,请查看Fiddle
请注意,即使有内容(如果您不使用CSS更改它),
br
的高度,请使用:
distance = = y.offsetTop - x.offsetTop;
offset()
也使用了getBoundingClientRect()
。下面的代码是有意义的。 - Allan Stepps