jQuery航点,在视口中心而不是顶部激活

jquery waypoints, activate when in center of viewport instead of top?

本文关键字:顶部 激活 航点 视口 jQuery      更新时间:2023-09-26

所有文档都谈到航点何时到达视口顶部,但我希望当航点的任何部分位于视口中心时触发。

如果我向下滚动,这段代码效果很好,但是当我向上滚动时,它不起作用,不知所措。

$('.section').waypoint(function(direction) {
    highlight('#' + this.id);
}, {
    context: '#scroll',
    offset: function (direction) {
        return $(this).height();
    }
});

我尝试了下面的代码和几个变体,它甚至从未命中任何一个 return 语句。

$('.section').waypoint(function(direction) {
    highlight('#' + this.id);
}, {
    context: '#scroll',
    offset: function (direction) {
        if (direction == 'down') {
            return -$(this).height();
        } else {
            return 0;
        }
    }
});

所以现在我正在尝试这个,基于航点示例,但 $active.id 不像 this.id 那样工作,所以我的函数"突出显示"失败。

$('.section').waypoint(function (direction) {
    var $active = $(this);
    if (direction == 'down') {
        $active = $active.prev();
    }
    if (!$active.length) {
        $active = $(this);
    }
    highlight($active.id);
}, {
    context: '#scroll',
    offset: function (direction) {
        return $(this).height();
    }
});

offset 选项不采用方向参数。我很想知道您是否从文档中的某个地方得到它,因为如果在offset函数中使用direction的部分,那就是一个错误。

您可以使用 % 偏移量告诉当元素顶部碰到视口中间时要触发的航点:

offset: '50%'

如果在向上滚动和向下滚动时需要具有不同的偏移量,最好通过创建两个不同的航点来实现:

var $things = $('.thing');
$things.waypoint(function(direction) {
  if (direction === 'down') {
    // do stuff
  }
}, { offset: '50%' });
$things.waypoint(function(direction) {
  if (direction === 'up') {
    // do stuff
  }
}, {
  offset: function() {
    // This is the calculation that would give you
    // "bottom of element hits middle of window"
    return $.waypoints('viewportHeight') / 2 - $(this).outerHeight();
  }
});