2016-07-07 160 views
1

每次滾動一個像素數量時我都想顯示一個div,並且在滾動一些圖像後淡出它。我發現了一些邏輯,但最後還是有衝突,div又一次消失了,因爲每當scroll> 250時它都會淡入。 我該如何解決它?使用jquery滾動時淡入淡出

$('#1').hide(); 

$(window).scroll(function() { 
    if ($(this).scrollTop() > 250) { //use `this`, not `document` 
    $('#1').fadeIn(); 
    } 
    if ($(this).scrollTop() > 1250) { //use `this`, not `document` 
    $('#1').fadeOut(); 
    } 
}); 

回答

1

僅當scrollTop值小於或等於1250時才顯示元素。

if ($(this).scrollTop() > 250 && $(this).scrollTop() <= 1250){ 
    $('#1').fadeIn(); 
} 

雖然可以使用stop()停止先前的動畫。

$(window).scroll(function() { 
    if ($(this).scrollTop() > 250) { 
    if ($(this).scrollTop() > 1250) 
     $('#1').stop().fadeOut(); 
    else 
     $('#1').stop().fadeIn(); 
    } 
}); 
1

這個問題是因爲你的邏輯有缺陷。您需要滿足scrollTop不在當前if條件範圍內的情況。在上面的例子中,我不得不改變id所以,它沒有以數字開頭爲Chrome瀏覽器有問題

$(window).scroll(function() { 
    if ($(this).scrollTop() > 250 && $(this).scrollTop() < 1250) { 
    $('#1').fadeIn(); 
    } else { 
    $('#1').fadeOut(); 
    } 
}); 

Working example

注:試試這個。