找到最接近位置的html元素(相对或绝对)

psy*_*tik 22 html javascript jquery

给定绝对或相对位置(顶部和左侧)是否有任何方法可以获得最接近这些坐标的html元素?

或者,有没有办法设计一个选择器(或使用一些jQuery构造)来枚举元素,然后找到哪些是关闭提供的坐标?假设元素集很小且有限.

Sag*_*agi 21

我已经构建了一个jQuery方法,它在集合中返回最接近offset的元素:

jQuery.fn.closestToOffset = function(offset) {
    var el = null,
        elOffset,
        x = offset.left,
        y = offset.top,
        distance,
        dx,
        dy,
        minDistance;
    this.each(function() {
        var $t = $(this);
        elOffset = $t.offset();
        right = elOffset.left + $t.width();
        bottom = elOffset.top + $t.height();

        if (
            x >= elOffset.left &&
            x <= right &&
            y >= elOffset.top &&
            y <= bottom
        ) {
            el = $t;
            return false;
        }

        var offsets = [
            [elOffset.left, elOffset.top],
            [right, elOffset.top],
            [elOffset.left, bottom],
            [right, bottom],
        ];
        for (var off in offsets) {
            dx = offsets[off][0] - x;
            dy = offsets[off][1] - y;
            distance = Math.sqrt(dx * dx + dy * dy);
            if (minDistance === undefined || distance < minDistance) {
                minDistance = distance;
                el = $t;
            }
        }
    });
    return el;
};
Run Code Online (Sandbox Code Playgroud)

笔记:

  1. 如果偏移位于其中一个元素内,则将返回该元素.
  2. 我正在循环四个偏移,因为这可以提供最佳精度.

像这样使用它:

$('div.myCollection').closestToOffset({left: 5, top: 5});
Run Code Online (Sandbox Code Playgroud)