Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

javascript - Measure distance between two HTML elements' centers

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Pythagorean Theorem

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.

Distance equation

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...