gpt4 book ai didi

javascript - 如何在鼠标移动时从当前鼠标位置获取最近的 anchor

转载 作者:太空宇宙 更新时间:2023-11-04 15:54:12 30 4
gpt4 key购买 nike

    $('p').on('mousemove',function(event) {
link = $(event.target).find('a');
//to find the nearest link and store in the link variable
console.log(link.html());//to print the link in console
});

我尝试了这个,但我只能找到段落中的第一个链接但我想找到靠近我的鼠标位置的链接

最佳答案

您可以使用document.elementFromPoint(x, y);并创建某种 jQuery 插件

首先,要查看正在运行的代码,请检查 fiddle

下面代码的使用示例:

$("p").nearest("a", 10);

但是下面的代码只是检查具有所提供距离的元素周围的框。如果它没有返回任何元素,您可以进一步使用它,并选中元素周围距离为 20 像素的框,然后是 30 像素,依此类推。取决于您的需求。

$.fn.nearest = function(selector, radius) {
var position = this.offset();

if (!radius) radius = 10; // pixels

var positions = [];
var elements = [];

// so, move up and left by the value of radius variable (lets say its 10)
// start from the -10 -10 px corner of the element and move all the way to
// +10 +10 coordinats to the right bottom corner of the element
var startX = position.left - radius;
var startY = position.top - radius;
var endX = position.left + this.outerWidth(true) + radius;
var endY = position.top + this.outerHeight(true) + radius;

var positions = [];

// create horizontal lines
// --------------
// your element
// --------------
for (var x = startX; x < endX; x++) {
// creates upper line on the startY coordinate
positions.push([x, startY]);
// creates bottom line on the endY coordinate
positions.push([x, endY]);
}

// create the vertical positions
// | |
// | your element |
// | |
for (var y = startY; y < endY; y++) {
// creates the left line on the startX coordinate
positions.push([startX, y]);
// creates the right line on the endX coordinate
positions.push([endX, y]);
}

// so now the positions array contains all the positions around your element with a radius that you provided
for (var i = 0; i < positions.length; i++) {
// just loop over the positions, and get every element
var position = positions[i];
var x = position[0];
var y = position[1];

var element = document.elementFromPoint(x, y);
// if element matches with selector, save it for the returned array
if ($(element).is(selector) && elements.indexOf(element) === -1) elements.push(element);
}

return $(elements);
}

关于javascript - 如何在鼠标移动时从当前鼠标位置获取最近的 anchor ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42852872/

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