如何在滚动时反转css转换以实现飞入/飞出效果

时间:2013-09-04 12:19:28

标签: javascript jquery html css css3

我正试图让飞入/飞出效果发生

向下滚动 - 在

中制作动画

向上滚动动画

为了获得与nizo网站类似的效果

http://nizoapp.com/

我使用了我在Stackoverflow上找到的代码“使用css向下滚动元素” 确定元素是否在视口中的屏幕上,然后为其设置动画。

   $(window).scroll(function () {

        /* Check the location of each desired element */
        $('.article').each(function (i) {

            var bottom_of_object = $(this).position().top + $(this).outerHeight();
            var bottom_of_window = $(window).scrollTop() + $(window).height();

            /* If the object is completely visible in the window, fade it it */
            if (bottom_of_window > bottom_of_object) {

                $(this).animate({
                    'opacity': '1'
                }, 500);

            }

        });

    });

哪个效果很好。

我已将其添加到此演示页面,并对其进行了修改。

http://saigonhousefinder.com/potteryone/fadinonscroll.html

(可能不会长寿)

我已经使用css过渡来获得我正在寻找的效果。飞入飞出等等

然后我发现.....这个功能做同样的事情

function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();
    var elemTop = $(elem).offset().top;
    return ((elemTop <= docViewBottom) && (elemTop >= docViewTop));
}

反正.......

当向下滚动时,我无法使动画生效。

但是当我们向上滚动时,我无法让动画反向移动

我认为最简单的方法是检测你是否向下滚动,所以我找到了这个方法/功能

(function () {
    var previousScroll = 0;

    $(window).scroll(function () {
       var currentScroll = $(this).scrollTop();
       if (currentScroll > previousScroll){



  $("#div").fadeIn("slow");
       }
       else {

  $("#div").fadeOut("slow");



       }
       previousScroll = currentScroll;
    });
}());

哪种方法效果很好,但我无法正常工作。

此时我可以检测到元素在屏幕上何时可见,然后为其添加效果。

我需要它来检测相同元素何时开始离开屏幕并对其应用其他效果。

如何使这项工作得到任何帮助都很棒

度过愉快的一天

1 个答案:

答案 0 :(得分:1)

这是一个非常简洁的演示和一个伟大的概念!我玩了一些代码,似乎你几乎就在那里。您需要检测屏幕顶部何时符合元素顶部,因此仅在加载页面时计算一次偏移量。我添加了一个20px的阈值,所以它提前了一点。让我知道如果这有帮助,可以根据您想要调用它的方式和时间进行调整。这是一个简单的js小提琴演示 http://jsfiddle.net/XhAhR/23/

(function () {

  var previousScroll = 0;
  var elemTop = $("#div").offset().top;
  $("#div").fadeOut();

  $(window).scroll(function () {
   var currentScroll = $(this).scrollTop();

   if (currentScroll > previousScroll){
           if(elemTop -20 > currentScroll){
               $("#div").fadeIn("slow");
           }
   }
   else {
       if(elemTop - 20 > currentScroll){
           $("#div").fadeOut("slow");
       }
   }
   previousScroll = currentScroll;
  });
}());