网页使背景保持不变,直到向下滚动足够远

Webpage make background stay the same until scroll down far enough

本文关键字:滚动 背景 网页      更新时间:2023-09-26

不确定这是否可能,我试图在html页面上放置一个新颖类型的文档,我希望背景保持每一章相同,但一旦他们向下滚动到下一章,背景需要更改为该章的(更改可以是即时的或顺利的无关紧要)

提示吗?

当然是使用jQuery库…

在你的页眉或页脚包含jquery库…

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

然后在上面的脚本之后包含这个块…

    <script type="text/javascript">
    $(document).ready(function(){
        bg.init();
        $(window).scroll(function(){        
                bg.updateBG();
        });
    });
    var bg = {
    current_image: 'chapter_1',
    offsets: new Array(),
    init: function(){
        $('.chapter').each(function(){
            bg.offsets.push($(this).height());
        });
    },
    updateBG: function(){
        var offset = $(window).scrollTop();
        var total = bg.offsets.length;
        var current_image;
        var chapter = 1;
        for(var i = 0; i < total; i ++)
        {
            if(offset > bg.offsets[i])
            {
                chapter = (i + 1);
                current_image = 'chapter_' + chapter;
                // this will leave the last image overwrite as the current image
            }
        }
        if(current_image != bg.current_image)
             {
                  $('body').css('background', 'url(/path-to-image/' + current_image + '.jpg) no-repeat center center');
                  bg.current_image = current_image;
                  // only update if a change is noticed
             }
        }
    };
        </script>

这里是一个示例html来理解这个复杂的JS…

<div id="container">
    <div class="chapter" id="chapter_1">
        some content
    </div>
    <div class="chapter" id="chapter_2">
        some content
    </div>
    <div class="chapter" id="chapter_3">
        some content
    </div>
</div>

内容显然在#container元素中。另外,将路径更新为真实图像。有更顺畅的过渡方式,但你可以决定如何做,然后询问细节。

同样,窗口高度除以2是为了在页面底部交换图像。

看看scrollTop()如何通过JQuery计算当前视图位置:http://api.jquery.com/scrollTop/

简单演示:http://jsfiddle.net/AlienWebguy/rpCEr/

下面是应用了渐变动画的相同演示:http://jsfiddle.net/AlienWebguy/rpCEr/1/

您可以使用JavaScript获取当前滚动位置,章节元素的偏移量,并相应地更改背景。(注意,这段代码不是跨浏览器的-你需要做一些改变以完全兼容IE)

http://jsfiddle.net/minitech/9LYpA/