使用 jQuery 限制滚动时的垂直背景位置

Limit vertical background position on scrolling with jQuery

本文关键字:垂直 背景 位置 滚动 jQuery 使用      更新时间:2023-09-26

我正在使用这个函数:

$(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 位置限制为某个值(例如 100px),因此背景图像中心在达到此值后保持可见。

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

因为烘焙地面图像非常大,所以最好在全屏上看到:https://jsfiddle.net/esedic/vw2n16r8/4/embedded/result/

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

感谢您的帮助!

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

$(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');
});