更新时间:2023-02-01 22:33:14
获取他们的位置,并使用毕达哥拉斯定理来确定他们之间的距离...
(function(){
var getPositionAtCenter = function(element){
var data = element.getBoundingClientRect();
返回{
x:data.left + data.width / 2,
y:data.top + data.height / 2
};
};
var getDistanceBetweenElements = function(a,b){
var aPosition = getPositionAtCenter(a);
var bPosition = getPositionAtCenter(b);
返回Math.sqrt(
Math.pow(aPosition.x - bPosition.x,2)+
Math.pow(aPosition.y - bPosition.y,2)
);
};
var distance = getDistanceBetweenElements(document.getElementById(x),
的document.getElementById( Y));
})();
上(原点位于左上角),因此您可以想象一个右键菜单,
您可以修改方程以得到 c 的值, code>通过获得对方的平方根。
然后,您只需将值(
x
和 y
是元素之间的差异,一旦它们的中心被确定ned),你会发现斜边的长度,这是元素之间的距离。 If I have HTML elements as follows:
<div id="x"></div>
<div id="y" style="margin-left:100px;"></div>
...how do I find the distance between them in pixels using JavaScript?
Get their positions, and use the Pythagorean Theorem to determine the distance between them...
(function() {
var getPositionAtCenter = function (element) {
var data = element.getBoundingClientRect();
return {
x: data.left + data.width / 2,
y: data.top + data.height / 2
};
};
var getDistanceBetweenElements = function(a, b) {
var aPosition = getPositionAtCenter(a);
var bPosition = getPositionAtCenter(b);
return Math.sqrt(
Math.pow(aPosition.x - bPosition.x, 2) +
Math.pow(aPosition.y - bPosition.y, 2)
);
};
var distance = getDistanceBetweenElements(document.getElementById("x"),
document.getElementById("y"));
})();
The Pythagorean Theorem relates to the relationship between the sides of a right-angled triangle.
The elements are plotted on a Cartesian coordinate system (with origin in top left), so you can imagine a right-angled triangle between the elements' coordinates (the unknown side is the hypotenuse).
You can modify the equation to get the value of c
by getting the square root of the other side.
Then, you simply plug the values in (the x
and y
are the differences between the elements once their centers are determined) and you will find the length of the hypotenuse, which is the distance between the elements.