航点和 Inview,使用通配符选择器跟踪多个元素



我在页面上有多个 id 像ss-section-storyss-section-problemss-section-solution的部分,我正在尝试跟踪每个部分何时进入和退出视口。问题是,使用我拥有的当前代码,它仅使用idss-section跟踪第一部分。我希望能够跟踪进入和退出的每个部分。

.JS

var inview = new Waypoint.Inview({
element: $('section[id^="ss-section"]')[0],
enter: function(direction) {
console.log(this.element.id + ' enter');
},
entered: function(direction) {
console.log(this.element.id + ' entered');
},
exit: function(direction) {
console.log(this.element.id + ' exit');
},
exited: function(direction) {
console.log(this.element.id + ' exited');
}
})

我知道它必须只跟踪第一部分,因为在element选项上,它仅限于该数组中的[0],但是当我删除它时,我将在这些控制台.log语句上未定义。

我希望能够做到这一点,但从文档来看,它没有这样的语法:

$('section[id^="ss-section"]').Waypoint.Inview({
enter: function(direction) {
console.log(this.element.id + ' enter');
},
entered: function(direction) {
console.log(this.element.id + ' entered');
},
exit: function(direction) {
console.log(this.element.id + ' exit');
},
exited: function(direction) {
console.log(this.element.id + ' exited');
}
})

关于如何仅使用Waypoint.Inview的一个实例来跟踪每个单独部分的任何建议

首先,你可以进行收集:

var $collection = $('section[id^="ss-section"]');

然后你通过它进行迭代:

$collection.each(function () {
new Waypoint.Inview({
element: this,
enter: function(direction) {
console.log(this.element.id + ' enter');
},
entered: function(direction) {
console.log(this.element.id + ' entered');
},
exit: function(direction) {
console.log(this.element.id + ' exit');
},
exited: function(direction) {
console.log(this.element.id + ' exited');
}
})
})

就这样。至少它对我有用。

最新更新