当元素进入窗口执行功能时

时间:2010-03-22 20:47:34

标签: javascript jquery

当我向下滚动窗口时,如何在元素上执行函数?

2 个答案:

答案 0 :(得分:1)

function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
}

via https://stackoverflow.com/questions/487073/jquery-check-if-element-is-visible-after-scroling

答案 1 :(得分:1)

我不妨在这里发帖作为回答:

function elementInView($elem, vps, vpe) {
    var elempos = $elem.position(); 
    var pagestart = elempos.top + vps;
    var pageend = elempos.top + vps + $elem.height();
    var offset = $elem.height() - Math.max(0,vps-pagestart) - Math.max(0,pageend-vpe);    
    return (vpe > 0 && offset > -200); 
}

$('#container').bind('scroll', function() {
    var $container = $(this);
    var vps = $container.scrollTop();
    var vpe = vps + $container.height();

    $('li', '#container').each(function() {
        var $this = $(this);
        if (elementInView($this,vps,vpe)) {
            // $this is now in view
        }
    });
});

我意识到这有一些性能问题,可以进行优化,但它应该是一个开始。