Locating DOM element by absolute coordinates

后端 未结 3 1984
刺人心
刺人心 2020-12-16 18:45

Is there a simple way to locate all DOM elements that \"cover\" (that is, have within its boundaries) a pixel with X/Y coordinate pair?

3条回答
  •  孤街浪徒
    2020-12-16 18:47

    This does the job (fiddle):

    $(document).click(function(e) {
        var hitElements = getHitElements(e);
    });
    
    var getHitElements = function(e) {
        var x = e.pageX;
        var y = e.pageY;
        var hitElements = [];
    
        $(':visible').each(function() {
            var offset = $(this).offset();
            if (offset.left < x && (offset.left + $(this).outerWidth() > x) && (offset.top < y && (offset.top + $(this).outerHeight() > y))) {
                hitElements.push($(this));
            }
        });
    
        return hitElements;
    }​
    

    When using :visible, you should be aware of this:

    Elements with visibility: hidden or opacity: 0 are considered visible, since they still consume space in the layout. During animations that hide an element, the element is considered to be visible until the end of the animation. During animations to show an element, the element is considered to be visible at the start at the animation.

    So, based on your need, you would want to exclude the visibility:hidden and opacity:0 elements.

提交回复
热议问题