当页面到达特定位置时执行并停止 JavaScript

Execute & Stop JavaScript when page reach a certain position

我有一个脚本,我只想在用户到达位置 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;
}

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

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 作为您的依赖项