2015-06-18 85 views
0

我有一個腳本,只有當用戶到達位置X(在導航欄下方)時纔會執行,並且僅當用戶再次到達此位置X時纔會停止腳本我的導航欄)。當頁面到達某個位置時執行並停止JavaScript

如何達到這個效果?

編輯:

我如何能實現這樣的代碼:

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; 
} 
+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爲你的依賴