2014-05-03 73 views
3

我正嘗試使用Javascript來檢測用戶在我的網站上向下滾動超過一定高度時的情況,然後當他們到達滾動斷點時,我的「社交」圖標就會淡入。如何在滾動上只運行一次jQuery動畫?

我想弄清楚的是我怎麼才能運行fadeTo一旦alpha命中1並鎖定它?因此,當用戶再次上下滾動時,fadeIn不會一遍又一遍地發生,除非它們啓動頁面重新載入,這會重置所有內容。

//SCROLL 
$(window).on("scroll", function() { 
//SOCIAL ICONS 
if ($(this).scrollTop() > 1750) { 
    $(".img-social .gith").stop(true).fadeTo(250, 1); 
    $(".img-social .inst").stop(true).fadeTo(450, 1); 
    $(".img-social .twit").stop(true).fadeTo(650, 1); 
    $(".img-social .drib").stop(true).fadeTo(850, 1); 
    $(".img-social .link").stop(true).fadeTo(1050, 1); 
} else { 
    $(".img-social .gith").stop(true).fadeTo(10, 0); 
    $(".img-social .inst").stop(true).fadeTo(10, 0); 
    $(".img-social .twit").stop(true).fadeTo(10, 0); 
    $(".img-social .drib").stop(true).fadeTo(10, 0); 
    $(".img-social .link").stop(true).fadeTo(10, 0); 
} 
}); 

感謝

回答

2

只要把下面的第一個if條件offscroll事件中的代碼,一旦你運行該代碼:

$(window).on("scroll.socialIcon", function() { 
    if ($(this).scrollTop() > 1750) { 
     // ... 
     $(window).off("scroll.socialIcon"); // last line 
    } else { 
     //... 
    } 
}); 

因此,scroll.socialIcon(名稱空間)事件不再響應。

+0

真棒,這真的很好,謝謝編輯!我有一些其他的東西,我褪色滾動,所以scroll.mySection完美的工作! – Monstr92

+0

很高興知道,歡迎您@ Monstr92 :-) –

+0

好奇,因爲我沒有嘗試過:這不會阻止淡出,因爲它不再監聽滾動嗎?你能解釋更多關於命名空間的聽衆嗎? – eriese

3

使用Boolean記錄是否是發生與否:

// SET BOOLEAN 
var scrolled = false; 

//SCROLL 
$(window).on("scroll", function() { 
//SOCIAL ICONS 
    if ($(this).scrollTop() > 1750 && !scrolled) { 
     $(".img-social .gith").stop(true).fadeTo(250, 1); 
     $(".img-social .inst").stop(true).fadeTo(450, 1); 
     $(".img-social .twit").stop(true).fadeTo(650, 1); 
     $(".img-social .drib").stop(true).fadeTo(850, 1); 
     $(".img-social .link").stop(true).fadeTo(1050, 1); 
     scrolled = true; 
    } else { 
     $(".img-social .gith").stop(true).fadeTo(10, 0); 
     $(".img-social .inst").stop(true).fadeTo(10, 0); 
     $(".img-social .twit").stop(true).fadeTo(10, 0); 
     $(".img-social .drib").stop(true).fadeTo(10, 0); 
     $(".img-social .link").stop(true).fadeTo(10, 0); 
     scrolled = false; 
    } 
}); 
+0

謝謝,我忘了在jS中使用布爾值。我會試試這個。 – Monstr92

+0

我認爲!滾動需要是scrollTop> 1750語句中的單獨if語句。否則,當它不能進入​​第一個if時,它會立即再次設置爲false。 –