parallax.js是一款简单的,轻量级的、但功能非常强大的视觉差特效引擎插件。它可以对智能设备点击运动的方向作出反应,不需要任何识别方向,检测位置的设备,只需要游标(鼠标运动的方向等)的方向。它可以检测智能设备的方向。你可以将它作为 jQuery 插件来使用,也可以以纯 JS 的方式来使用。
![]() |
---|
该视觉差特效的基本HTML结构使用的是一个无序列表,每一个列表项给它们一个class layer和一个data-depth属性来指定该层的深度。深度为0的层将是固定不动的,深度为1的层运动效果最激烈的层。0-1之间的层会根据值来相对移动。
<ul id="scene"> <li class="layer" data-depth="0.00"><img src="layer1.png"></li> <li class="layer" data-depth="0.20"><img src="layer2.png"></li>
<li class="layer" data-depth="0.40"><img src="layer3.png"></li>
<li class="layer" data-depth="0.60"><img src="layer4.png"></li>
<li class="layer" data-depth="0.80"><img src="layer5.png"></li>
<li class="layer" data-depth="1.00"><img src="layer6.png"></li>
</ul>
首先要初始化视觉差效果,可以选择指定的DOM元素之后,创建一个新的Parallax对象。
var scene = document.getElementById('scene');
var parallax = new Parallax(scene);
层运动的计算规则,每一个层的运动量依赖于3个因素:
1)scalarX 和 scalarY 的值
2)父 DOM 元素的尺寸大小
3)一个 parallax 场景中层的depth值
计算的公式如下:
xMotion = parentElement.width * (scalarX / 100) * layerDepthyMotion = parentElement.height * (scalarY / 100) * layerDepth
所以在场景中一个data-depth为0.5的层,它的scalarX和scalarY值都为10(默认值),它的父容器的尺寸为1000px x 1000px,那么这个层在x和y方向的总运动量就为:
xMotion = 1000 * (10 / 100) * 0.5 = 50 # 50px of positive and negative motion in xyMotion = 1000 * (10 / 100) * 0.5 = 50 # 50px of positive and negative motion in y
下面是一些可用的配置参数,这些参数也可以在HTML标签中使用data属性来指定。
![]() |
---|
Data 属性举例:
<ul id="scene" data-calibrate-x="false" data-calibrate-y="true"
data-invert-x="false" data-invert-y="true" data-limit-x="false" data-limit-y="10"
data-scalar-x="2" data-scalar-y="8" data-friction-x="0.2" data-friction-y="0.8" data-origin-x="0.0"
data-origin-y="1.0">
<li class="layer" data-depth="0.00"><img src="graphics/layer1.png"></li>
<li class="layer" data-depth="0.20"><img src="graphics/layer2.png"></li>
<li class="layer" data-depth="0.40"><img src="graphics/layer3.png"></li>
<li class="layer" data-depth="0.60"><img src="graphics/layer4.png"></li>
<li class="layer" data-depth="0.80"><img src="graphics/layer5.png"></li>
<li class="layer" data-depth="1.00"><img src="graphics/layer6.png"></li>
</ul>
构造函数方式举例:
var scene = document.getElementById('scene');
var parallax = new Parallax(scene, {
calibrateX: false,
calibrateY: true,
invertX: false,
invertY: true,
limitX: false,
limitY: 10,
scalarX: 2,
scalarY: 8,
frictionX: 0.2,
frictionY: 0.8,
originX: 0.0,
originY: 1.0});
如果你将 Parallax.js 作为 jQuery 或 Zepto 插件来使用,可以如下方式使用:
$('#scene').parallax();
带参数:
$('#scene').parallax({
calibrateX: false,
calibrateY: true,
invertX: false,
invertY: true,
limitX: false,
limitY: 10,
scalarX: 2,
scalarY: 8,
frictionX: 0.2,
frictionY: 0.8,
originX: 0.0,
originY: 1.0});
官网地址 : http://matthew.wagerfield.com/parallax/
Github地址 :https://github.com/wagerfield/parallax/tree/master