本文介绍了查找距离位置最近的html元素(相对或绝对)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定绝对或相对位置(上&左)有没有办法让这些坐标最近的html元素?



或者,有没有办法任何方式来制作一个选择器(或使用一些jQuery构造)来枚举元素,然后找到哪个接近所提供的坐标?假设这组元素很小且有限。

解决方案

$ b $我已经构建了一个jQuery方法,返回集合中最靠近偏移量的元素:

  jQuery.fn.closestToOffset =函数(偏移量){
var el = null,
elOffset,
x = offset。左边,
y = offset.top,
距离,
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 offset = [
[elOffset.left,elOffset.top],
[right,elOffset.top],
[ ($)
[right,bottom],
];
for(var off in offset){
dx = offset [off] [0] - x ;
dy = offset [off] [1] - y;
distance = Math.sqrt(dx * dx + dy * dy);
if(minDistance === undefined || distance < minDistance){
minDistance = di姿态;
el = $ t;
}
}
});
return el;
};

注意:


  1. 如果偏移量在其中一个元素中,它将被返回。

  2. 我正在循环四个偏移量,因为这提供了最佳精度。

像这样使用它:

  $('div.myCollection')。closestToOffset({left:5,top:5}); 


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 craft a selector (or use some jQuery construct) to enumerate elements and then find which is closes to the provided co-ordinates? Assume that the set of elements is small and finite.

解决方案

I've built a jQuery method that returns closest element to offset, within the collection:

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;
};

Notes:

  1. If the offset is inside one of the elements, it will be returned.
  2. I'm looping through four offsets, because this gives the best accuracy.

Use it like this:

$('div.myCollection').closestToOffset({left: 5, top: 5});

这篇关于查找距离位置最近的html元素(相对或绝对)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 00:18