您的位置:首页 > Web前端 > HTML

基于Parallax设计HTML视差效果

2017-01-22 11:34 295 查看
年关将至,给大家拜年。

最近时间充裕了一点,给大家介绍一个比较有意思的控件:Parallax。它可以用来实现鼠标移动时,页面上的元素也做偏移的视差效果。在一些有表现层次,布局空旷的页面上,用来做Head最合适不过了,大家可以看这个官方Demo

一、准备工作

如果不想用cdn的话,就下载

1、在github上下载parallax

2、下载jquery

二、实现效果

这里只介绍最简单的使用方法,先上代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>恭喜发财</title>
<script type="text/javascript" src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="//cdn.bootcss.com/parallax/2.1.3/jquery.parallax.min.js"></script>
<script type="text/javascript" src="//cdn.bootcss.com/parallax/2.1.3/parallax.min.js"></script>
<style>
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
/*** 定位 ***/
#DIV_title {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
margin: 0;
}
#DIV_title li {
width: 100%;
height: 100%;
}
#DIV_title_bg {
position: absolute;
width: 110%;
height: 110%;
top: -5%;
left: -5%;
background: url("http://dwz.cn/58F0u5") no-repeat 50% 100%;
background-size: cover;
}
#DIV_title h1 {
position: absolute;
left: 50%;
font-size: 100px;
font-weight: bold;
color: yellow;
}
#H1_title_1 {
margin-left: -250px;
top: 100px;
}
#H1_title_2 {
margin-left: -200px;
top: 200px;
}
#H1_title_3 {
margin-left: -150px;
top: 300px;
}
#H1_title_4 {
margin-left: -100px;
top: 400px;
}
#H1_title_5 {
margin-left: -50px;
top: 500px;
}
</style>
</head>

<body>
<ul id="DIV_title">
<li class="layer" data-depth="0.10"><div id="DIV_title_bg"></div></li>
<li class="layer" data-depth="0.15"><h1 id="H1_title_1">新</h1></li>
<li class="layer" data-depth="0.60"><h1 id="H1_title_2">年</h1></li>
<li class="layer" data-depth="0.30"><h1 id="H1_title_3">快</h1></li>
<li class="layer" data-depth="0.50"><h1 id="H1_title_4">乐</h1></li>
<li class="layer" data-depth="1.00"><h1 id="H1_title_5">!</h1></li>
</ul>

<script type="text/javascript">

$(function() {
var parallax = new Parallax(document.getElementById("DIV_title"));
console.log(parallax);
});

</script>

</body>
</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%居中为基准,左右移动定位;

四、Demo效果

http://codepen.io/anon/pen/qRmjOW

请无视主页面下面滚动条的空白,这是因为iframe导致的。

转载请注明原址:http://www.cnblogs.com/lekko/p/6339827.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: