gpt4 book ai didi

javascript - 查找离位置最近的 html 元素(相对或绝对)

转载 作者:技术小花猫 更新时间:2023-10-29 11:57:01 62 4
gpt4 key购买 nike

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

或者,有没有什么方法可以制作一个选择器(或使用一些 jQuery 构造)来枚举元素,然后找到哪个与提供的坐标接近?假设元素集很小且有限。

最佳答案

我构建了一个 jQuery 方法,它返回集合中最接近偏移的元素:

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

注意事项:

  1. 如果偏移量在元素之一的内部,它将被返回。
  2. 我正在遍历四个偏移量,因为这提供了最佳的准确性。

像这样使用它:

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

关于javascript - 查找离位置最近的 html 元素(相对或绝对),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2337630/

62 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com