我有一个在页面加载时具有固定位置的容器,其高度等于窗口高度。它必须被定位为“固定”(?),因为当滚动大于1px时,覆盖文本会弹出它,并且它们的高度必须等于窗口高度。 如果scrollTop大于窗口高度的一半,页面将自动滚动到下一部分,并从该容器中删除固定位置。
以下是代码:
$(window).on('scroll.a', function () {
var windowHeight = $(window).outerHeight();
var scrollTopMask = $(window).scrollTop();
var slideAfter = windowheight/2;
if (scrollTopMask > slideAfter) {
$('.container').addClass('not-fixed');
$('html, body').animate({
scrollTop: $('#nextSection').offset().top
}, 700);
$(window).off('scroll.a');
} else if (scrollTopMask < slideAfter) {
$('.container').removeClass('not-fixed');
}});
问题是我必须off()
滚动功能才能在执行功能并满足条件后继续滚动。当scrollTop === 0
并且用户再次向下滚动时,有没有办法重新启动功能?
答案 0 :(得分:0)
如果用户滚过slideAfter
,只需使用标记来存储状态。如果是false
,则继续使用逻辑,否则只需返回:
var hasScrolledPast = false;
$(window).on('scroll.a', function () {
var windowHeight = $(window).outerHeight();
var scrollTopMask = $(window).scrollTop();
var slideAfter = windowheight/2;
if (scrollTopMask > slideAfter) {
// If user has already scrolled past, don't do anything
if (hasScrolledPast)
return;
$('.container').addClass('not-fixed');
$('html, body').animate({
scrollTop: $('#nextSection').offset().top
}, 700);
// Update flag so that we know user has scrolled past
hasScrolledPast = true;
} else if (scrollTopMask < slideAfter) {
$('.container').removeClass('not-fixed');
// Reset scroll past flag
hasScrolledPast = false;
}
});
建议:您的用户可能会加载他/她的滚动位置已超出阈值的页面。但是,如果发生这种情况,则不会更新该标志,因为尚未在视口上触发滚动事件。在这种情况下,我建议将逻辑抽象为一个函数,你只需将该函数用作scroll事件的回调,并在页面加载时调用它:
var hasScrolledPast = false;
var scrollLogic = function() {
var windowHeight = $(window).outerHeight();
var scrollTopMask = $(window).scrollTop();
var slideAfter = windowheight/2;
if (scrollTopMask > slideAfter) {
// If user has already scrolled past, don't do anything
if (hasScrolledPast)
return;
$('.container').addClass('not-fixed');
$('html, body').animate({
scrollTop: $('#nextSection').offset().top
}, 700);
// Update flag so that we know user has scrolled past
hasScrolledPast = true;
} else if (scrollTopMask < slideAfter) {
$('.container').removeClass('not-fixed');
// Reset scroll past flag
hasScrolledPast = false;
}
};
// Evaluate on scroll
$(window).on('scroll.a', scrollLogic);
// Evaluate on page load/DOM ready
scrollLogic();