视差滚动 - 滚动绝对元素

时间:2014-01-02 13:06:47

标签: jquery css

我的页面上有一个绝对的位置“英雄”部分。当向下滚动页面时,我希望下面的内容滚动到英雄部分的顶部。

要执行此操作,请在向下滚动页面时更新较低内容的top位置。但是,这样做似乎会将英雄单位推离页面,而不是简单地滚动它的顶部。

HTML:

<div class="container">
    <section class="hero">
        <div class="hero-content">
             <h1>loud noises.</h1>
             <p class="strapline">we make loud noises so you don't have to</p>
        </div>
    </section>
    <div class="inner">
        <section class="feature-1">
             <h2>Some awesome feature</h2>
        </section>
        <section class="feature-2">
             <h2>Some awesome feature</h2>
        </section>
        <footer></footer>
    </div>
</div>

CSS:

.hero {
    position: absolute;
    background-color: #3498db;
    text-align: center;
    overflow: hidden;
    z-index: 0;
    background-color: #fff;
    /*max-height: 768px; set the height limit here */
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}

.inner {
    position: relative;
    top: 100%;
    z-index: 100;
}

JavaScript的:

$(window).scroll(function () {
    $('.inner').css('top', $('.hero').height() - $(window).scrollTop());
});

演示:

http://fiddle.jshell.net/benfosterdev/LycXL/

2 个答案:

答案 0 :(得分:2)

您似乎已经给.hero绝对值,而不是尝试使用fixed

<强> CSS

.hero {
    position: fixed;
}

<强> Working jsFiddle Demo

答案 1 :(得分:-1)

然后应该修复背景。

添加

  

背景附件:固定的;

到你的.hero:课后。

相关问题