将div滚动到视图时触发事件

时间:2015-10-07 19:03:05

标签: javascript jquery

当用户滚动到页面的顶部和底部时,我能够注册一个事件,但是当用户滚动到页面的下方时,无法触发事件。我在中间SELECT * FROM ( SELECT TOP 1 * FROM Alerts WHERE AlertType='2000' ORDER BY Datetime ASC UNION ALL SELECT TOP 1 * FROM Alerts WHERE AlertType='2003' ORDER BY Datetime DESC ) t 有一个div,当它在向下滚动时进入浏览器的视口时需要触发。

我需要这样做没有一个额外的插件。

HTML

#below-fold

的jQuery

<div class="top">TOP</div>
<div id="below-fold">Fold</div>
<div class="bottom">Bottom</div>

JSFIDDLE:LINK

2 个答案:

答案 0 :(得分:0)

你应该在你的IF中测试[element] .offset()。top:

编辑:要仅检查第一个输入事件,您可以使用示例中的标记。

$(function () {
    var $win = $(window);
    var $fold = $('#below-fold');
    var inTheFold = false;

    $win.scroll(function () {

        console.log($win.scrollTop());
        console.log($fold.offset().top);
        console.log(inTheFold);

        if ($win.scrollTop() >= $fold.offset().top && $win.scrollTop() <= $fold.offset().top+$fold.height() )
        {  
            if (!inTheFold) {
              inTheFold = true;
              console.log("VIEWED BELOW THE FOLD");
              mixpanel.track(
                "User Scrolled Below Fold", {
                "url": window.location.href
              });
            }

        } else if ($win.scrollTop() <= $fold.offset().top || $win.scrollTop() >= $fold.offset().top+$fold.height() ) {

            if (inTheFold) {
                inTheFold = false;
              console.log("EXITED THE FOLD");
              mixpanel.track(
                "EXITED THE FOLD", {
                "url": window.location.href
              });
            }

        }
    });

});

演示:http://jsfiddle.net/rndam8ns/7/

答案 1 :(得分:0)

将else if改为:

else if ($win.scrollTop() >= $('#below-fold').position().top - $win.height() && $win.height() + $win.scrollTop()  < $(document).height())

更新:http://jsfiddle.net/rndam8ns/6/

var triggered = false添加到混音中,这样它只会在向下滚动时触发一次,当它滚动到顶部时,它会重置并再次触发