如何在鼠标移动时从当前鼠标位置获取最近的锚点

时间:2017-03-17 08:45:12

标签: javascript jquery

    $('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
     });

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

2 个答案:

答案 0 :(得分:1)

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

首先,要查看操作中的代码,请查看fiddle

以下代码的使用示例:

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

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

$.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);
}

答案 1 :(得分:0)

您也可以尝试悬停而不是鼠标移动

   *ngIf="auth.loggedIn()"