-1

我正在寻找一个函数,它可以从 DOM 中获取一个元素并确定它是否垂直地出现在用户的视线中?

4

1 回答 1

1

我搜索了一个可以获取元素并检查它是否在用户正在查看的当前滚动高度的函数。我最终尝试了一堆不能完全满足我需要的功能,然后我自己构建了。由于我没有找到这样的功能,我现在与大家分享,以防将来有人需要它!:P这没有使用任何框架或插件。

function visible(a, t){
    // a => element
    // t => tolerance, how much pixels can be hidden and still return true
    var w_top = window.pageYOffset || document.documentElement.scrollTop,
        w_hgh = window.outerHeight,
        a_top = 0,
        a_hgh = a.offsetHeight;

    while(a.tagName.toLowerCase() !== 'body') {
        a_top += a.offsetTop;
        a = a.offsetParent;
    }

    var b = (w_top + w_hgh) - (a_top + a_hgh);

    if(b > (0 - t) && b < (w_hgh - a_hgh + t)){
        return true;
    }
    return false;
}

一个使用的例子:

var element = document.getElementById('id');
if(!visible(element, 50)){
    element.focus();
}
于 2013-08-11T14:18:16.753 回答