如何获取当前显示在屏幕上的第一个可见DOM元素?

如何获取当前显示在屏幕上的第一个可见DOM元素?

问题描述:

如何获取当前显示在屏幕上的第一个可见DOM元素?

How to get first visible DOM element currently showing on the screen ?

我尝试了

var el = document.elementFromPoint(x,y)

var el = document.elementFromPoint(x, y)

并在while循环中增加y坐标,但是问题是当文档上有css多列时,它是行不通的,在这种情况下<返回html>标记,而不是实际元素.有什么办法可以让我真正地将元素显示在可用于CSS列的屏幕的(顶部,左侧)?

and increasing the y coordinates in a while loop, but the problem is it does not work when there are css multi columns on the document, in that case the < html > tag is returned, not the actual element. Is there any way I can really get the element on the (top,left) of the screen which works for css columns ?

这是一个非常基本的示例,该示例仅获取距top最远的元素.这只是一个开始,因为您可能还需要考虑left偏移量.

This is a very basic example that just gets the element that is the furthest to the top. It's just a start, because you may want to take into consideration the left offset as well.

您将要排除bodyhtml元素(如下所示),因为它们将始终排在第一位.

You'll want to exclude the body and html elements (as shown below), since they will always be first.

var first;
$(':visible').not('body, html').each(function() {
    if (typeof first == 'undefined') {
        first = $(this);
    } else if ($(this).offset().top < first.offset().top) {
        first = $(this);
    }
});
first.addClass('highlight');