2013-05-30 112 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

没关系,都修好了,再次感谢! –