网页使背景保持不变,直到向下滚动足够远
Webpage make background stay the same until scroll down far enough
不确定这是否可能,我试图在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/相关文章:
- 背景图像顶部的滚动图像不移动
- 修复弹出框并使背景滚动
- 背景滚动,内容上下匹配
- 缩小并更改滚动时的背景导航栏
- 试图让我的引导程序navabar背景淡出滚动在我的wordpress主题
- 导航栏在向下滚动时会更改背景,但在向上滚动时不会更改回来
- 使用 jQuery 限制滚动时的垂直背景位置
- 向上滚动导航栏背景淡出
- 滚动的背景图像仍在闪烁
- 如何创建具有滚动背景图像的可滚动文本区域
- 连续滚动背景
- jQuery 在滚动背景上动画颜色不变
- 视差滚动背景图像自动放大和缩小
- 如何使网站滚动背景不移动和工具栏自动最小化
- 在Javascript或CSS缓慢滚动背景
- 引导模式滚动背景内容
- HTML5画布/JavaScript(滚动背景/相机)
- 我想使页面与固定的内容和滚动背景
- jQuery/CSS:固定覆盖不允许滚动背景
- 动态jQuery CSS具有三状态滚动背景位置根据状态变化