私信  •  关注

Brent Barbata

Brent Barbata 最近创建的主题
Brent Barbata 最近回复了
9 年前
回复了 Brent Barbata 创建的主题 » 当内容位于可见视区时启动jquery动画

这将考虑元素所具有的任何填充、边框或边距以及大于视口本身的元素。

function inViewport($ele) {
    var lBound = $(window).scrollTop(),
        uBound = lBound + $(window).height(),
        top = $ele.offset().top,
        bottom = top + $ele.outerHeight(true);

    return (top > lBound && top < uBound)
        || (bottom > lBound && bottom < uBound)
        || (lBound >= top && lBound <= bottom)
        || (uBound >= top && uBound <= bottom);
}

用这样的话来称呼它:

var $myElement = $('#my-element'),
    canUserSeeIt = inViewport($myElement);

console.log(canUserSeeIt); // true, if element is visible; false otherwise