jquery - 具有视差的背景图像

标签 jquery html css

所以我需要网站的一部分与背景图像有视差。问题是代码从网站开始计算视差(这是一个长的向下滚动类型的网站),当我到达提到的部分时,背景已经太高了。代码中是否需要某种“延迟”,以便在滚动 X 像素后开始出现视差?这里的代码:

JQUERY:

$(document).ready(function() {
    // Cache the Window object
    $window = $(window);

    $('section[data-type="background"]').each(function() {
        var $bgobj = $(this); // assigning the object

        $(window).scroll(function() {

            // Scroll the background at var speed
            // the yPos is a negative value because we're scrolling it UP!                              
            var yPos = -($window.scrollTop() / $bgobj.data('speed'));

            // Put together our final background position
            var coords = '50% ' + yPos + 'px';

            // Move the background
            $bgobj.css({
                backgroundPosition: coords
            });
        }); // window scroll Ends
    });
});

HTML:

<section id="background" data-type="background" data-speed="5">
    <div class="container">
        <div class="shadow-block"><img src="images/shadow-b.png" alt="" class="scale-with-grid"/></div>
            <div class="quote two-thirds column" >  
            </div>
            </div>
</section>

CSS:

#background {
    background: url(../images/big-bg.jpg)no-repeat center center;
    background-size:cover;
    width: 100%;
    height:500px;
    padding: 40px 0;
    overflow: hidden;
    position: relative;
}

最佳答案

你能不能不要这样?

var Top = $(document).scrollTop();
    if(Top < 200){ 
    //Then do the parallax stuff...
}

关于jquery - 具有视差的背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19842024/

相关文章:

asp.net - 我使用了 css,现在无法滚动

javascript - Phonegap应用程序无法连接到移动设备上的数据库

javascript - 如何在 JavaScript 中为 setInterval() 设置自定义时间?

javascript - 滚动 "stack"个 DOM 对象

javascript - 如何使 js 函数通用以在我的表单上的任何地方工作? (干燥)

html - 将页脚保持在包装/内容的下方或底部

javascript - 如何自动暂停其他音频播放器并仅播放 Wix 网站上选择的音频播放器?

html - 使用 max-width 100% 和 height auto 时图像被剪切

javascript - 使用ajax获取div的内容

html - 如何给段落添加边距?