自动移动视差背景

Avatar of Chris Coyier
Chris Coyier

DigitalOcean 为您旅程的每个阶段提供云产品。立即开始使用 200 美元的免费额度!

前一段时间,我做了一个关于视差背景的 小演示。简单回顾一下,视差就是背景有多个不同的层,每个层以不同的速度移动,从而产生非常独特的 3D 效果(想想刺猬索尼克)。在最初的演示中,唯一可以看到视差效果的方法是调整浏览器窗口的大小。

最近,Paul Hayes 采用了这个例子并加以改进。他使用了非常酷的 -webkit-transition 属性,使视差效果可以在无需调整浏览器窗口大小或使用 JavaScript 的情况下移动。Paul 做得非常棒,演示效果也很好,但当然,因为它使用了专有的 CSS 扩展,所以它只在非常现代的基于 WebKit 的浏览器(Safari 4 和 Google Chrome)中有效。

虽然 Paul 的示例是未来此类效果的理想实现方式,但我认为在原始示例中添加一点 JavaScript 并发布一个自动移动版本可能会很酷,这个版本应该可以在所有浏览器中运行*。

 

查看演示   下载文件

 

工作原理

每个“层”只是一个覆盖整个屏幕的绝对定位的 div。

<div id="background"></div>
<div id="midground"></div>
<div id="foreground"></div>
#background {
	background: url(../images/background.png) repeat 5% 5%;
	position: absolute;
	top: 0; left: 0; right: 0; bottom: 0;
	z-index: 100;
}

#midground {
	background: url(../images/midground.png) repeat 20% 20%;
	position: absolute;
	top: 0; left: 0; right: 0; bottom: 0;
	z-index: 200;
}

#foreground {
	background: url(../images/foreground.png) repeat 90% 110%;
	position: absolute;
	top: 0; left: 0; right: 0; bottom: 0;
	z-index: 300;
}

背景图片是重复的,并使用百分比设置。百分比是使视差效果正常工作的关键。但在这个新的 JavaScript 版本中,我们将覆盖这些百分比并对这些值进行动画处理。这需要使用 jQuery 的 backgroundPosition 插件,因为 jQuery 本身无法对 backgroundPosition 属性进行动画处理。

<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="js/jquery.backgroundPosition.js" type="text/javascript"></script>
<script type="text/javascript">
	$(function(){
	
	  $('#midground').css({backgroundPosition: '0px 0px'});
	  $('#foreground').css({backgroundPosition: '0px 0px'});
	  $('#background').css({backgroundPosition: '0px 0px'});
	
		$('#midground').animate({
			backgroundPosition:"(-10000px -2000px)"
		}, 240000, 'linear');
		
		$('#foreground').animate({
			backgroundPosition:"(-10000px -2000px)"
		}, 120000, 'linear');
		
		$('#background').animate({
			backgroundPosition:"(-10000px -2000px)"
		}, 480000, 'linear');
		
	});
</script>

请注意,在开始动画之前,我们必须在 JavaScript 中重置 backgroundPosition。很奇怪……但这是插件正常工作的一个要求。

延长动画时长

动画函数中的那些大数字(例如 120000)代表千分之一秒。所以 120000 = 120 秒 = 2 分钟。更改这些数字,您可以延长或缩短动画时长。它不是无限的……可能有一种方法可以做到这一点,我只是没有完全想通。也许可以将动画抽象成一个函数,然后可以在回调函数中(或其他方式)再次调用它。

*视差效果高度依赖于透明度。如果您需要它在 IE 6 中工作,请查看 Unit PNG 修复DD_belatedPNG