ten*_*tar 16 html javascript distance
如果我有HTML元素如下:
<div id="x"></div>
<div id="y" style="margin-left:100px;"></div>
Run Code Online (Sandbox Code Playgroud)
...如何使用JavaScript找到它们之间的距离(以像素为单位)?
ale*_*lex 30
得到他们的位置,并使用毕达哥拉斯定理来确定他们之间的距离......
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")
);
Run Code Online (Sandbox Code Playgroud)
如果您不支持浏览器Math.hypot(),则可以使用:
Math.sqrt(
Math.pow(aPosition.x - bPosition.x, 2) +
Math.pow(aPosition.y - bPosition.y, 2)
);
Run Code Online (Sandbox Code Playgroud)
毕达哥拉斯定理涉及直角三角形的两侧之间的关系.
元素绘制在笛卡尔坐标系上(原点位于左上角),因此您可以想象元素坐标之间的直角三角形(未知边是斜边).
您可以c通过获取另一侧的平方根来修改等式以获得值.

然后,您只需插入值(一旦确定了它们的中心,x并且y是元素之间的差异),您将找到斜边的长度,即元素之间的距离.
| 归档时间: |
|
| 查看次数: |
17132 次 |
| 最近记录: |