Find html element nearest to position (relative or absolute)

后端 未结 5 1822
隐瞒了意图╮
隐瞒了意图╮ 2020-12-10 01:52

Given absolute or relative position (top & left) is there any way to get the nearest html element to these co-ordinates?

Or alternately, is there any way to craf

5条回答
  •  心在旅途
    2020-12-10 02:12

    I used @Felix answer and applied it to vanilla Js for my requirements, I know it's an old question but if anyone needs it

    function getClosestChoice(x, y, elements) {
      let closestEl,
        minDist,
        offset;
    
      elements.forEach((el) => {
        offset = { left: el.offsetLeft, top: el.offsetTop };
        offset.left += el.offsetWidth / 2;
        offset.top += el.offsetHeight / 2;
        const dist = Math.sqrt(
          (offset.left - x) * (offset.left - x) + (offset.top - y) * (offset.top - y)
        );
        if (!minDist || dist < minDist) {
          minDist = dist;
          closestEl = el;
        }
      });
      return closestEl;
    }
    

提交回复
热议问题