jQuery窗口滚动停止触发用户滚动

jQuery window scroll stop firing as user scrolls

本文关键字:滚动 用户 窗口 jQuery      更新时间:2023-09-26

当用户向下滚动一定数量的像素时,我修复标题。但是,是否有一种方法可以在用户满足逻辑后停止调用窗口滚动函数?我认为这对性能不利。查看我的控制台截图(http://d.pr/i/OHDX)

$window.scroll(function() {
    if ($window.scrollTop() > 100) {
        $('.header').addClass('fixed');
        console.log('fix header'); 
    }
    else {
        $('.header').removeClass('fixed');
        console.log('unfix header'); 
    }
}

您必须不断检查滚动位置。我猜当用户滚动到100时,您会想要取消修复它?

当前的实现在性能方面很好。您可以添加的一件事是检查类是否已经添加,或者保留一个开关,以便您知道是否存在类(而不是检查)。

$window.scroll((function() {
    var fixed = false, elem;
    return function () {
        var should_fix = $window.scrollTop() > 100;
        elem = elem || $('.header');
        if (should_fix !== fixed) {
            if (should_fix) {
                elem.addClass('fixed');
                console.log('fix header'); 
            } else {
                elem.removeClass('fixed');
                console.log('unfix header'); 
            }
            fixed = should_fix;
        }
    };
}()) // immediate invocation, because it's awesome