年关将至,给大家拜年。
最近时间充裕了一点,给大家介绍一个比较有意思的控件: Parallax 。它可以用来实现鼠标移动时,页面上的元素也做偏移的视差效果。在一些有表现层次,布局空旷的页面上,用来做Head最合适不过了,大家可以看这个 官方Demo 。
如果不想用cdn的话,就下载
1、在 github上 下载parallax
2、下载jquery
这里只介绍最简单的使用方法,先上代码:
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="UTF-8">
5 <title>恭喜发财</title>
6 <script type="text/javascript" src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
7 <script type="text/javascript" src="//cdn.bootcss.com/parallax/2.1.3/jquery.parallax.min.js"></script>
8 <script type="text/javascript" src="//cdn.bootcss.com/parallax/2.1.3/parallax.min.js"></script>
9 <style>
10 html, body {
11 width: 100%;
12 height: 100%;
13 margin: 0;
14 padding: 0;
15 }
16 /*** 定位 ***/
17 #DIV_title {
18 width: 100%;
19 height: 100%;
20 position: absolute;
21 top: 0;
22 left: 0;
23 margin: 0;
24 }
25 #DIV_title li {
26 width: 100%;
27 height: 100%;
28 }
29 #DIV_title_bg {
30 position: absolute;
31 width: 110%;
32 height: 110%;
33 top: -5%;
34 left: -5%;
35 background: url("http://dwz.cn/58F0u5") no-repeat 50% 100%;
36 background-size: cover;
37 }
38 #DIV_title h1 {
39 position: absolute;
40 left: 50%;
41 font-size: 100px;
42 font-weight: bold;
43 color: yellow;
44 }
45 #H1_title_1 {
46 margin-left: -250px;
47 top: 100px;
48 }
49 #H1_title_2 {
50 margin-left: -200px;
51 top: 200px;
52 }
53 #H1_title_3 {
54 margin-left: -150px;
55 top: 300px;
56 }
57 #H1_title_4 {
58 margin-left: -100px;
59 top: 400px;
60 }
61 #H1_title_5 {
62 margin-left: -50px;
63 top: 500px;
64 }
65 </style>
66 </head>
67
68 <body>
69 <ul id="DIV_title">
70 <li class="layer" data-depth="0.10"><div id="DIV_title_bg"></div></li>
71 <li class="layer" data-depth="0.15"><h1 id="H1_title_1">新</h1></li>
72 <li class="layer" data-depth="0.60"><h1 id="H1_title_2">年</h1></li>
73 <li class="layer" data-depth="0.30"><h1 id="H1_title_3">快</h1></li>
74 <li class="layer" data-depth="0.50"><h1 id="H1_title_4">乐</h1></li>
75 <li class="layer" data-depth="1.00"><h1 id="H1_title_5">!</h1></li>
76 </ul>
77
78 <script type="text/javascript">
79
80 $(function() {
81 var parallax = new Parallax(document.getElementById("DIV_title"));
82 console.log(parallax);
83 });
84
85 </script>
86
87 </body>
88 </html>
先忽略css,来看最核心的框架:
1、DIV_title list。此list的层次结构可以根据自己的需要进行调整,记得list子级的li带上class="layer"。
2、data-depth属性。此属性关系到景深,取0~1,越大的数字表示越靠间,相对其它元素动得越快。
3、js初始化。在dom加载完,通过new Parallax()方法即可把指定元素纳入视差效果。
4、更多的参数,参考前面的github链接。
再来看一下css:
1、通过绝对定位把各个元素放到不同的位置;
2、实现了bg图也可动的效果。#DIV_title_bg元素的css之所以要加-5%,就是在背景也可动时,不出现空白所以特意加了位移,图片也对应地加大了10%。
3、各个子元素以50%居中为基准,左右移动定位;
http://codepen.io/anon/pen/qRmjOW
请无视主页面下面滚动条的空白,这是因为iframe导致的。