向下滚动时滑入的盒子

Avatar of Chris Coyier
Chris Coyier 发布

DigitalOcean 为您旅程的每个阶段提供云产品。立即开始使用 200 美元的免费额度!

我正在玩我的新 Nexus 7(我真的很想拥有一台真正的 Android 设备),我注意到随附的 Google+ 应用中有一个很酷的小效果。当您向下滑动时,新的内容模块会向上滑动到位。视频在此处效果最佳

我们可以做到!这是一个非常简单的两步过程

当窗口滚动时,检查模块是否可见

jQuery 有一个 :visible 选择器,但这不是我们这里需要的。我们需要查看元素的任何部分是否在视觉视口中。也就是说,一个元素在技术上可能是可见的,但位于屏幕外。我们可以通过数学计算来确定一个元素是否在视觉视口中。窗口有多宽多高,滚动到多远,元素有多宽多高,它位于哪里等等。幸运的是,jquery-visible 插件很好地总结了这些数学运算。

(function($) {

  /**
   * Copyright 2012, Digital Fusion
   * Licensed under the MIT license.
   * http://teamdf.com/jquery-plugins/license/
   *
   * @author Sam Sehnert
   * @desc A small plugin that checks whether elements are within
   *     the user visible viewport of a web browser.
   *     only accounts for vertical position, not horizontal.
   */

  $.fn.visible = function(partial) {
    
      var $t            = $(this),
          $w            = $(window),
          viewTop       = $w.scrollTop(),
          viewBottom    = viewTop + $w.height(),
          _top          = $t.offset().top,
          _bottom       = _top + $t.height(),
          compareTop    = partial === true ? _bottom : _top,
          compareBottom = partial === true ? _top : _bottom;
    
    return ((compareBottom <= viewBottom) && (compareTop >= viewTop));

  };
    
})(jQuery);

剩下的就是当窗口“滚动”时使用它来添加一个类名。

$(window).scroll(function(event) {
  
  $(".module").each(function(i, el) {
    var el = $(el);
    if (el.visible(true)) {
      el.addClass("come-in"); 
    } 
  });
  
});

CSS 将处理滑入效果

.come-in {
  transform: translateY(150px);
  animation: come-in 0.8s ease forwards;
}
.come-in:nth-child(odd) {
  animation-duration: 0.6s; /* So they look staggered */
}

@keyframes come-in {
  to { transform: translateY(0); }
}

如果元素已经可见,则保持原样

因此,我们不会在第一次滑动时对已经可见的模块触发动画,我们将添加一个类名来移除该动画。我们还可以在这里提高效率,“缓存”选择器,这样我们就不必在每次滚动事件(会触发很多次)上查找它们。

var win = $(window);
var allMods = $(".module");

// Already visible modules
allMods.each(function(i, el) {
  var el = $(el);
  if (el.visible(true)) {
    el.addClass("already-visible"); 
  } 
});

win.scroll(function(event) {
  
  allMods.each(function(i, el) {
    var el = $(el);
    if (el.visible(true)) {
      el.addClass("come-in"); 
    } 
  });
  
});

这就行了

查看 CodePen 上 Chris Coyier 的作品
从底部滑入的盒子
(@chriscoyier)
CodePen 上。

请注意,CSS 过渡可以是任何东西。它们可以从侧面滑入,可以使用缩放和不透明度,看起来像是飞入的。可以涉及颜色。随便。