-
Notifications
You must be signed in to change notification settings - Fork 0
/
ch3_cssparallax_js.html
67 lines (64 loc) · 1.41 KB
/
ch3_cssparallax_js.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS Parallax</title>
<style>
body {
padding: 0px;
margin: 0px;
}
.layer {
position: absolute;
width: 100%;
height: 256px;
}
#back {
background: #3BB9FF url(images/back1.png);
}
#middle {
background: transparent url(images/back2.png);
}
#front {
background: transparent url(images/back3.png);
}
</style>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(function () {
var speed = 0, // 速度
$back = $('#back'), // 将3个div缓存起来
$middle = $('#middle'),
$front = $('#front'),
xPos = 0, // 背景图片的x坐标
$win = $(window);
// mousemove 根据鼠标位置计算速度
// mouseout 将速度计为0
$(document).mousemove(function (e) {
var halfWidth = $win.width() / 2;
speed = e.pageX - halfWidth;
speed /= halfWidth;
}).mouseout(function (e) {
speed = 0;
});
setInterval(function () {
xPos += speed;
$back.css({
backgroundPosition: xPos + 'px 0px'
});
$middle.css({
backgroundPosition: 2 * xPos + 'px 0px'
});
$front.css({
backgroundPosition: 3 * xPos + 'px 0px'
});
}, 30);
});
</script>
</head>
<body>
<div id="back" class="layer"></div>
<div id="middle" class="layer"></div>
<div id="front" class="layer"></div>
</body>
</html>