简体   繁体   English

在滚动条上设置相对位置背景y元素

[英]Set relative based position background y element on scroll

jQuery(function ($) {       

    $(window).scroll(function() { 
        var y = $(this).scrollTop();

        if (y > 360) {
            var pos_yvalue = y - 294;
            $('.site-header .wrap').css('background-position-y',
            pos_yvalue.toString() + 'px');
        }
    });
});

With above I want to set an image in the wrap-header ( .site-header .wrap ) to a background-position-y relative to the y-position of the scroll. 通过上面的内容,我想将环绕头( .site-header .wrap )中的图像设置为相对于滚动的y位置的背景位置y。

So when I scroll above 360px then I want to position the background-image of site-header .wrap to be 66 and when it is 362 the background-image of the wrap should be 65 etc. 因此,当我在360px以上滚动时,我想将site-header .wrap的背景图像定位为66,当它为362时,包装的背景图像应为65等。

Above code would represent the values 66, 67, 68 etc instead of counting downwards like this: 66, 65, 64, 63,62,61 etc.. 上面的代码将代表值66、67、68等,而不是像这样向下计数:66、65、64、63、62、61等。

For some reason I can't get my head around this one. 由于某种原因,我无法理解这一点。

I noticed some syntax errors that may be part of your problem if you're not linting your code or have an IDE that lets you know. 如果您不添加代码或拥有可让您知道的IDE,我会注意到一些语法错误,这可能是您问题的一部分。

As is, your code should look like: 照原样,您的代码应如下所示:

jQuery(function ($) {       

    $(window).scroll(function() { 
        var y = $(this).scrollTop();

        if (y > 360) {
            var pos_yvalue = y - 294;
            $('.site-header .wrap').css('background-position-y',
        pos_yvalue.toString() + 'px');
        }
    });
});

You're missing some closing )'s. 您缺少一些结束的)。 Otherwise the code appears to add the background position to the .site-header element. 否则,该代码似乎将背景位置添加到.site-header元素。 Are you going for a fixed header that sticks to the top of the page? 您要固定在页面顶部的固定标题吗?

It was actually just a matter of calculation: 实际上这只是一个计算问题:

if (y > 360) {
    var minus_y = ( y - 295 ) - 66;   
    var pos_yvalue = 66 - minus_y;
    $('.site-header .wrap').css('background-position-y', pos_yvalue.toString() + 'px');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM