jQuery waypoints 插件 - 在不可见时删除 class

jQuery waypoints plugin - remove class when out of view

我正在使用 waypoints 插件

$('.thing').waypoint(function(direction) {
    jQuery(".block7").addClass("active");
});

现在我想修改它,使添加的 class 在离开浏览器视图时立即从 .thing 元素中删除。我要在上面的代码中添加什么?

您可以通过查看 direction 来完成。如果相同的偏移量适用于添加和删除 class,您可以将其放入您的处理程序

var waypoint = new Waypoint({
  element: $('.thing'),
  handler: function(direction) {
    if (direction == 'up') {
      $(".block7").removeClass("active");
    } else {
      $(".block7").addClass("active");
    }
  },
  offset: '100%'
})

或者如果你想要不同的偏移量,你可以制作 2 waypoints。

var waypoint = new Waypoint({
  element: $('.thing'),
  handler: function(direction) {
    $(".block7").addClass("active");
  },
  offset: '75%'
})

var waypoint2 = new Waypoint({
  element: $('.thing'),
  handler: function(direction) {
    if (direction == 'up') {
      $(".block7").removeClass("active");
    }
  },
  offset: '100%'
})

这是一个代码笔 - http://codepen.io/anon/pen/oZqMdJ

这可以通过使用额外的路点来解决,该路点测试方向是否等于向下并使用负偏移量来确定何时触发处理程序。当项目不在浏览器视图中时,负偏移量是让它工作的关键。

var resetWaypoint = new Waypoint({
  element: $('.thing'),
  handler: function(direction) {
    if (direction == 'down') {
      $(".block7").removeClass("active");
    } 
  },
  offset: '-10%'. /* where the magic happens. play with # til it works correctly with size of your element. */
})

更大的图景 - 如果您试图从本质上重置航路点,以便每次用户滚动经过它时,无论是向上还是向下,您都可以淡出 in/fade 一些东西,你会想要查看 'inview' 设置。更多信息在这里:

http://imakewebthings.com/waypoints/shortcuts/inview/