简体   繁体   English

jquery航点,在视口中心而不是顶部时激活?

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

All the documentation talks about when the waypoint reaches the top of the viewport, but I would like the trigger to happen when any part of the waypoint is in the center of the viewport. 所有文档都讨论了航点何时到达视口的顶部 ,但我希望当航点的任何部分位于视口的中心时触发器发生。

This code works fairly well if I'm scrolling down, but when I scroll up it doesn't work, obvoiusly. 如果我向下滚动,这段代码工作得相当好,但是当我向上滚动它时,它不起作用。

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

I tried the code below and a couple variants and it never even hits either of the return statements. 我尝试了下面的代码和几个变种,它甚至从未命中任何一个return语句。

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

    offset: function (direction) {
        if (direction == 'down') {
            return -$(this).height();
        } else {
            return 0;
        }
    }
});

So now I'm trying this, based on waypoint examples, but $active.id doesn't work like this.id so my function "highlight" fails. 所以现在我正在尝试这个,基于路标示例,但$ 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();
    }
});

The offset option does not take a direction parameter. offset选项不采用方向参数。 I'd love to know if you got that from somewhere in the documentation because if there's a section using direction in an offset function, it's a mistake. 我很想知道你是否从文档中的某个地方得到了这个,因为如果在offset函数中有一个使用direction的部分,那就错了。

You can tell a waypoint to trigger when the top of the element hits the middle of the viewport by using a % offset: 当元素的顶部通过使用%offset抵达视口的中间时,您可以告诉要触发的航点:

offset: '50%'

If you need to have a different offset when scrolling up versus scrolling down, this is best accomplished by creating two different waypoints: 如果在向上滚动和向下滚动时需要具有不同的偏移量,则最好通过创建两个不同的航点来实现:

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();
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM