固定内容滚动布局

时间:2014-12-31 15:35:14

标签: html css scroll fixed

以下网站在每个部分使用固定的背景图片,但如何为每个部分添加固定内容(文本,图像)并保持相同的滚动效果? http://tympanus.net/Blueprints/ScrollingLayout/

看看我的例子,以便更好地了解我的需求:

http://jsfiddle.net/w919y0gb/

我的尝试:

#wrapper {
    position: relative;
    height: 500px;
    width: 500px;
    overflow: scroll;
}
.section {
    position: relative;
    height: 100%;
    width: 100%;
}
.content {
    position: fixed;
}

#s1 {
    background-color: #f00;
}
#s2 {
    background-color: #0f0;
}
#s3 {
    background-color: #00f;
}
#s1 .content {
}
#s2 .content {
    margin-top: -400px;
}
#s3 .content {
    margin-top: -800px;
}

<div id="wrapper">

    <div class="section" id="s1">
        <div class="content">hello1</div>
    </div>

    <div class="section" id="s2">
        <div class="content">hello2</div>
    </div>

    <div class="section" id="s3">
        <div class="content">hello3</div>
    </div>

</div>

我想要的是什么:

第一部分(红色)应该只显示“hello1”

第二个(绿色)仅“hello2”

第三个(蓝色)仅“hello3”

3 个答案:

答案 0 :(得分:0)

该参考网站只是使用background-image设置为fixed,如下所示:

FIDDLE

<强>更新

好的我明白了。您需要使用jquery和$(window).scroll()函数执行类似的操作:

NEW FIDDLE

使用positon: fixed只会将元素从文档流中分离出来,并且父级无法包含该元素,因此您需要使用absolute并根据{{1}进行定位给出它固定的外观。

答案 1 :(得分:0)

这样的事可能吗?有点hacky,但是如果你设置了部分高度就可以了。

$(document).ready(function(){
    $('.div3').hide();
    $('.div2').hide();
    $('.div1').show();
    $('#wrapper').scroll(function(){
        console.log($('#wrapper').scrollTop());
        if($('#wrapper').scrollTop() > 945){
            $('.div3').show();
            $('.div2').hide();
            $('.div1').hide();
        }
        else if ($('#wrapper').scrollTop() > 465) {
            $('.div3').hide();
            $('.div2').show();
            $('.div1').hide();
        }
        else {
            $('.div3').hide();
            $('.div2').hide();
            $('.div1').show();
        }
    });
});

更新小提琴:http://jsfiddle.net/w919y0gb/3/

有了这个,你也可以修改&#34; hello1 / hello2 / hello3&#34;的位置。处于相同的位置,而不是在不同的地方。或者你可以只有一个div来修改/替换hello1 / hello2 / hello3中的文本,具体取决于滚动位置。希望这有帮助!

答案 2 :(得分:0)

您还可以设置网页的高度,然后在向上或向下滚动时显示div。 下面是一个有效的例子:http://jsfiddle.net/ZyKar/1738/

    $(document).scroll(function () {
        var y = $(this).scrollTop();
        if (y > 0 && y < 400) {
            $('#s1').fadeIn();
            $('#s3').fadeOut();
            $('#s2').fadeOut();
        } else if (y > 400 && y < 800) {
            $('#s1').fadeOut();
            $('#s2').fadeIn();
            $('#s3').fadeOut();
        }else if (y > 800) {
            $('#s3').fadeIn();
            $('#s2').fadeOut();
        }

    });

滚动一定数量的像素后,div将开始出现并相互替换。

您可以通过在css中设置身体的高度来改变y的值,如小提琴中所示。然后,您可以将jQuery中的像素条件设置为您喜欢的任何值。