视差将背景图像滚动到永久视图中

时间:2013-12-07 00:47:01

标签: css3 twitter-bootstrap scroll parallax css-content

我想要的影响是我只能与Google+顶级导航效果相比较,并通过一些视差来比较。也就是说,当您向下滚动时,搜索栏会消失,您的左侧会显示一个小“工具栏”。我找到了一些jQuery来帮助我,在我弄明白之后我会搞砸。

我首先要做的是从条形图下方滚动背景图像(请参阅jfiddle)并向上滚动到最终保持放置的条形图。这是我到目前为止所得到的:

<section id="account-bar" class="shelf navbar-fixed-top">
    <div class="navbar-header">
        more...
    </div>
    <div class="navbar-collapse collapse">
        <ul class="nav navbar-nav">
            <li><a href="#">Links</a></li>
        </ul>
    </div>
</section>

与相关的css:

section#account-bar {
    background-color:#111;
    color:#ccc;
    font-size:1.1em;
    height:3.6em;
line-height:3.4em;
    text-align:right
}

section#account-bar:after {
    content:'';
    width:267px;
    height:46px;
    background:url('http://lorempixel.com/267/46/') no-repeat 0 0 scroll;
    background-size:267px 46px;
    top:0;
    left:0;
    position:absolute;
}

编辑:这是jsFiddle

1 个答案:

答案 0 :(得分:1)

虽然目前在纯CSS中不可能,但是使用window.onscrollscrollTop和几个if语句,您可以创建一个可爱的状态更改效果,类似于你正在寻找

查看Google Plus页面,导航上方有一些内容。因此,我按如下方式设置了我的HTML

<div class='topContent'>Top Content</div>
<nav>
    <div class='googleSlide'></div> <!--The image that slides in from the left-->
    <div class='navContent'>Nav bar content</div> <!-- Everything else in nav -->
</nav>

以下是我重要的CSS行以使其正常运行

.topContent { height:75px; /* Arbitrary but necessary value */ }
nav {  height:44px;  width:100%; }
nav div { float:left; }
.googleSlide {
    background-image: url(//ssl.gstatic.com/s2/oz/images/sprites/ribbon-nav-1x-69dd561f4c55d6702aadda4e3b4ce787.png);
    background-position:0 -100px;
    height: 44px; /* More arbitrary but necessary values */
    width: 44px;
    margin-left:-55px;
    transition: all 0.200s; /* To smooth the transition to the new state */
}

最后,我们有javascript让它全部正常工作

window.onscroll = function() { // Fires whiles the page scrolls
    var navigation = document.getElementsByTagName('nav')[0],
        slide = document.getElementsByClassName('googleSlide')[0];
    // Conditional to check whether scroll is past our marker, second conditional
    // to make sure that it doesn't keep firing when scrolling inside of the range
    if(document.body.scrollTop > 75  && navigation.style.background != 'white') {
        navigation.style.background = 'white';
        navigation.style.border = '1px solid black';
        navigation.style.position = 'fixed';
        slide.style.marginLeft = '0px';
    }
    // Same as above but toggles back to the original state
    if(document.body.scrollTop < 75 && navigation.style.background != 'grey') {
        navigation.style.background = 'grey';
        navigation.style.border = 'none';
        slide.style.marginLeft = '-55px';
        navigation.style.position = 'static';
        navigation.style.top = '0px';
    }
}

Demo

我不确定滚动背景究竟是什么意思,但是类似的方法可以让你得到你想要的东西