执行&页面到达某个位置时停止JavaScript

时间:2015-06-18 01:54:12

标签: javascript javascript-events

我有一个脚本,我只想在用户到达位置X(在我的导航栏下)时执行,并且只有当用户再次到达此位置X时(在我的导航栏下)才会停止。

如何达到这个效果?

编辑:

如何实现此代码:

    var reachedFromTop = false;
var reachedFromBottom = false;
$(window).scroll(function() {
    //After scrolling 100px from the top...
    if ($(window).scrollTop() > 100 ) {
        if (!reachedFromTop) something();
        reachedFromTop = true;
    } else if (reachedFromTop && otherCondition) {
        if (!reachedFromBottom) somethingElse();
        reachedFromBottom = true;
    }  
});

在我现有的脚本中:

var didScroll;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $('.main-navigation').outerHeight();

$(window).scroll(function(event){
    didScroll = true;
});

setInterval(function() {
    if (didScroll) {
        hasScrolled();
        didScroll = false;
    }
}, 250);

function hasScrolled() {
    var st = $(this).scrollTop();

   if(Math.abs(lastScrollTop - st) <= delta)
        return;

if (st > lastScrollTop && st > navbarHeight){
$('.main-navigation').removeClass('nav-down').addClass('nav-up');
} else {
if(st + $(window).height() < $(document).height()) {
$('.main-navigation').removeClass('nav-up').addClass('nav-down');
}
}

lastScrollTop = st;
}

1 个答案:

答案 0 :(得分:0)

你应该可以做这样的事情。

var reachedFromTop = false;
var reachedFromBottom = false;
$(window).scroll(function() {
    //After scrolling 100px from the top...
    if ($(window).scrollTop() > 100 ) {
        if (!reachedFromTop) something();
        reachedFromTop = true;
    } else if (reachedFromTop && otherCondition) {
        if (!reachedFromBottom) somethingElse();
        reachedFromBottom = true;
    }  
});

您需要包含jquery作为您的依赖