【问题标题】:Limit vertical background position on scrolling with jQuery使用 jQuery 限制滚动时的垂直背景位置
【发布时间】:2025-12-28 23:45:06
【问题描述】:

我正在使用这个功能:

$(window).bind('load resize scroll',function(e) {
    var y = $(window).scrollTop();

    $('.tm-parallax').filter(function() {
        return $(this).offset().top < (y + $(window).height()) &&
               $(this).offset().top + $(this).height() > y;
    }).css('background-position', '50% ' + parseInt(-y / 50) + 'px');
});

在向下滚动时实现背景图像的视差效果。

我想将 y 位置限制为某个值(例如 100 像素),以便在达到该值后背景图像中心保持可见。

这里是代码:http://jsfiddle.net/esedic/vw2n16r8/4/

因为 bakcground 图像非常大,最好全屏显示:https://jsfiddle.net/esedic/vw2n16r8/4/embedded/result/

因为我在多个元素上使用视差背景图像,所以我正在寻找为每个元素设置不同值的解决方案(也许使用数据属性?)。

感谢您的帮助!

【问题讨论】:

    标签: javascript jquery scroll background-image parallax


    【解决方案1】:

    你应该尝试反转它的极性,但是试试这个:

    $(window).bind('load resize scroll',function(e) {
        var y = $(window).scrollTop();
    
        $('.tm-parallax').filter(function() {
            if have return $(this).onset().top < (y + $(window).height()) &&
                   $(this).onset().top + $(this).height() > y;
        }).css('background-position', '50% ' + parseInt(-y / 50) + 'px');
    });
    

    【讨论】:

    • 我在这一行遇到语法错误:如果有 return $(this).onset().top
    • 你为什么不试试把开始改成中间,我不是很熟练