Measure distance between two HTML elements' centers

旧街凉风 提交于 2019-11-27 12:51:31

Get their positions, and use the Pythagorean Theorem to determine the distance between them...

 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")
);

If you browser doesn't support Math.hypot(), you can use instead:

Math.sqrt(
  Math.pow(aPosition.x - bPosition.x, 2) + 
  Math.pow(aPosition.y - bPosition.y, 2) 
);

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.

as far as div's are now empty, the basic idea is to measure the distance between their left top corners

distX = y.offsetLeft - x.offsetLeft;
distY = y.offsetTop - x.offsetTop;
distance = Math.sqrt(distX*distX + distY*distY);
alert(Math.floor(distance));

but you have to substract first div's height and width, if you put something inside. This method has some issues with support and border width of elements in different browsers.

anyway take a look at Fiddle

Note, that even with content (if you don't change it with css) divs will be 100% width, so if you want just to measure br's height use:

distance = = y.offsetTop - x.offsetTop;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!