javascript - 滚动的淡入问题

标签 javascript jquery fadein scrolltop

我正在尝试让我的内容在接近页面两端时淡入。当触发器设置在最顶部和最底部时,淡入淡出效果很好,但当我设置距离 (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");
        }
    });

最佳答案

发生的事情是你有两个相互对抗的函数:

第一个函数有一个“if-else”语句,第二个函数也有。 这意味着每次滚动时每个函数都会做一些事情。 有多种方法可以解决这个问题。

我要解决的方法是使用变量并更新约束。

假设我们有一个变量 onScreen,如果段落在屏幕上则值为 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;
     }
    }
 });

现在这不是最简洁的方法,我也不是故意的:通过使代码更广泛一些,我希望你能理解为什么它现在有效而以前无效(这样你实际上从中学习)。

我在 Fiddle 上为您准备了一个实例:http://jsfiddle.net/ycCAb/4/

我希望这能回答您的问题。祝你好运!

关于javascript - 滚动的淡入问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16844133/

相关文章:

jquery fadeIn 将不透明度保留为 0

jquery - 使用 jquery 使图像在图像加载时淡入

jquery - animate() 和 fadeIn() 没有按预期工作

javascript - 使用嵌套函数进行 JS 垃圾收集

jquery - 使用 div 作为网格?

javascript - 如何停止在 HTML 中重新加载 jquery

javascript - jQuery 处理按键组合

javascript - Ajax 自动刷新导致我的 jquery 嵌入脚本无休止地重复

javascript - Google Maps API V3 - 显示沿路线的进度

javascript - 如何优化 3 个条件 if else if 语句