2013-05-30 113 views
2

我試圖在達到某個接近頁面的各個端點時淡入內容。當觸發器設置爲最上方和最下方時,淡入淡出效果很好,但當我設置一個距離(200px)時,淡入淡出效果不再起作用,並且內容顯示出來。淡入淡出問題

$(window).scroll(function(){ 
     if($(window).scrollTop()<=200){ 
      $('#about .content').stop(true,true).fadeIn("5s"); 
     } 
     else { 
      $('#about .content').stop(true,true).fadeOut("10s"); 
     } 

    if ($(window).scrollTop() + $(window).height() >= $(document).height() - 200) { 
      $('#work .content').stop(true,true).fadeIn("5s"); 
     } else { 
      $('#work .content').stop(true,true).fadeOut("5s"); 
     } 
    }); 

回答

1

正在發生的事情是,你有兩個功能對彼此的工作:

第一個函數有一個「的if-else」語句和第二功能以及。這意味着每個函數都會做一些你每次滾動的東西。 有多種解決方法。

我會解決它的方式是使用變量並更新約束。

比方說,我們有一個可變屏幕上有值爲1,如果該段是在屏幕和值0,如果它是不是:

例如:

<div style="height: 800px">Example of scroll with fadeIn, fadeOut. 

<p style="margin-top:300px;">These paragraphs will go away when you have scrolled 
more than 10 pixels from the top. They will appear again when you have scrolled 
to a proximity of 50 pixels from the bottom. They will also appear if you go 
within a proximity of 10 pixels of the top again.</p> 

</div> 

現在的jQuery代碼:

var $onScreen = 1; 

$(window).scroll(function(){ 
if($(window).scrollTop() < 10){ 
     if ($onScreen == 0) 
     { 
     $("p:first").stop(true,true).fadeIn("slow", "linear"); 
     $onScreen = 1; 
     } 
    } 

if($(window).scrollTop() <= 20 && $(window).scrollTop() >= 10){ 
     if ($onScreen == 1) 
     { 
     $("p:first").stop(true,true).fadeOut("slow", "linear"); 
     $onScreen = 0; 
     } 
    } 

if ($(window).scrollTop() + $(window).height() >= $(document).height() - 50) { 
    if ($onScreen == 0) 
    { 
     $("p:first").stop(true,true).fadeIn("slow", "linear"); 
     $onScreen = 1; 
    } 
    } 
}); 

現在,這是不這樣做的最簡潔的方式,我不是故意這樣做的:通過使代碼有點更廣泛的,我希望你可以遵循,爲什麼現在的工作,並沒有w^ork之前(這樣你才能從中學習)。

我爲你準備了上擺弄活生生的例子:http://jsfiddle.net/ycCAb/4/

我希望這回答了你的問題。祝你好運!

+0

請注意,我以不允許快速滾動的方式創建了示例。因此,抓住滾動條並慢慢移動它以查看執行的功能。對於您的用法:更改fadeOut函數的參數以允許快速滾動(因爲目前它只有10px的邊距)。祝你好運! –

+0

真棒,感謝所有的幫助! 是它在某種程度上可能有內容的不透明性依賴於接近頂部/底部,這樣,而不是一個點是淡變觸發,它只會在完全不透明,當你一路向上滾動/下來,並會根據你的位置有一個範圍? –

+1

沒關係,都修好了,再次感謝! –