我在其父级“ stickyTo”中有一个名为“ sticky”的div,有多个父级div,在我的示例中,我只有两个,并且在该父级上的每个滚动都显示出一个粘性div,并将在该div上添加一个类。 >
var $sticky = jQuery('.sticky'); jQuery(window).on('scroll', function() { var scroll = jQuery(window).scrollTop(); $sticky.each(function(){ const $this = jQuery(this); const stickyTop = $this.offset().top; const stickyBottom = stickyTop + $this.outerHeight(); const $stickyTo = $this.parent(); const stickyToTop = $stickyTo.offset().top; const stickyToBottom = stickyToTop + $stickyTo.outerHeight(); if (stickyBottom >= stickyToBottom) { if (scroll < stickyTop) { //$sticky.addClass('fixed').removeClass('abs'); } else { //$sticky.addClass('abs'); } } else if (scroll > stickyToTop) { $sticky.addClass('stuck'); } else if (scroll < stickyToTop) { $sticky.removeClass('stuck'); } }) });
这里是我的FIDDLE,请告诉我我要做什么
当前代码的问题仅触发了第二个div,可能是我的each() function
在jquery中出了问题
我在其父对象“ stickyTo”内有一个名为“ sticky”的div,有多个父div,在我的示例中,我只有两个,并且在该父对象上的每个滚动显示了一个粘性div,并将添加一个类...] >
在每个函数中,应使用$(this)而不是$ sticky引用当前元素。 https://jsfiddle.net/dyc19oxL/
jQuery(window).on('scroll', function() {
var scroll = jQuery(window).scrollTop();
$sticky.each(function(){
const $this = jQuery(this);
const stickyTop = $this.offset().top;
const stickyBottom = stickyTop + $this.outerHeight();
const $stickyTo = $this.parent();
const stickyToTop = $stickyTo.offset().top;
const stickyToBottom = stickyToTop + $stickyTo.outerHeight();
if (stickyBottom >= stickyToBottom) {
if (scroll < stickyTop) {
//$sticky.addClass('fixed').removeClass('abs');
} else {
//$sticky.addClass('abs');
}
} else if (scroll > stickyToTop) {
**$(this).addClass('stuck');**
} else if (scroll < stickyToTop) {
**$(this).removeClass('stuck');**
}
})