簡體   English   中英

jquery航點,在視口中心而不是頂部時激活?

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

所有文檔都討論了航點何時到達視口的頂部 ,但我希望當航點的任何部分位於視口的中心時觸發器發生。

如果我向下滾動,這段代碼工作得相當好,但是當我向上滾動它時,它不起作用。

$('.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抵達視口的中間時,您可以告訴要觸發的航點:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM