练习1:轮播广告

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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
* {
margin: 0;
padding: 0;
}
#adv {
width: 940px;
margin: 0 auto;
}
#adv ul {
width: 120px;
height: 30px;
margin: 0 auto;
position: relative;
top: -30px;
}
#adv li {
width: 30px;
height: 30px;
list-style: none;
float: left;
color: #ccc;
cursor: pointer;
}
#adv li:first-child {
color: lightseagreen;
}
</style>
</head>
<body>
<div id="adv">
<img src="img/slide-1.jpg" alt="">
<ul>
<li class="dot">●</li>
<li class="dot">●</li>
<li class="dot">●</li>
<li class="dot">●</li>
</ul>
</div>
<script>
var img = document.querySelector('#adv>img');
var items = document.querySelectorAll('#adv li');
var timerId = 0;

for (var i = 0; i < items.length; i += 1) {
items[i].index = i;
items[i].addEventListener('mouseover', function(evt) {
index = evt.target.index;
changeItemsColor(index);
img.src = 'img/' + images[index];
if (timerId != 0) {
window.clearInterval(timerId);
timerId = 0;
}
});
items[i].addEventListener('mouseout', startIt);
}

var images = ['slide-1.jpg', 'slide-2.jpg', 'slide-3.jpg', 'slide-4.jpg'];
var index = 0;

startIt();

function startIt() {
if (timerId == 0) {
timerId = window.setInterval(function() {
index += 1;
index %= images.length;
changeItemsColor(index);
img.src = 'img/' + images[index];
}, 2000);
}
}

function changeItemsColor(index) {
for (var i = 0; i < items.length; i += 1) {
items[i].style.color = '#ccc';
}
items[index].style.color = 'lightseagreen';
}
</script>
</body>
</html>