一、简单轮播效果
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
* {
margin: 0;
padding: 0;
}
#adv {
width: 940px;
margin: 50px 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>
<script type="text/javascript">
// 函数声明会自动先声明
var index = 0;
var timeId;
var images = ['slide-1.jpg', 'slide-2.jpg', 'slide-3.jpg', 'slide-4.jpg'];
// 获取指定的标签名的标签(返回数组)
var img = document.querySelector('#adv>img');
var dots = document.querySelectorAll('#adv li');
// 绑定事件
for (var i = 0; i < dots.length; i += 1) {
// 动态绑定一个index属性(注意,这是关键)
dots[i].index = i;
dots[i].addEventListener('click', function(evt) {
var index = evt.target.index;
changeDotColor(index);
img.src = 'img/' + images[index];
if(timeId) {
window.clearInterval(timeId);
timeId = 0;
}
});
dots[i].addEventListener('mouseout', startIt);
}
startIt();
function startIt() {
if(!timeId) {
// 返回值是计时器id
timeId = window.setInterval(function() {
index += 1;
index %= images.length;
changeDotColor(index);
img.src = 'img/' + images[index];
}, 2000);
}
}
function changeDotColor(index) {
for (var i = 0; i < dots.length; i += 1) {
dots[i].style.color = '#ccc';
}
dots[index].style.color = 'lightseagreen';
}
</script>
</div>
</body>
</html>
二、缩略图预览效果
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>浏览效果</title>
<style type="text/css">
/* 动态绑定属性 */
* {
margin: 0;
padding: 0;
}
#imgBox {
width: 600px;
}
#imgBox #img1 {
width: 600px;
height: 300px;
margin-left: 30px;
margin-top: 30px;
}
#imgBox #img {
width: 50px;
height: 50px;
position: relative;
left: 200px;
}
</style>
</head>
<body>
<div id="imgBox">
<img id="img1" src="img/slide-1.jpg" >
<img id="img" src="img/thumb-1.jpg" />
<img id="img" src="img/thumb-2.jpg" />
<img id="img" src="img/thumb-3.jpg" />
</div>
<script type="text/javascript">
// 回调函数在for循环的时候并没有执行,所以回调函数中取不到正确的i值
// JavaScript是动态弱类型语言可以在运行时动态给对象添加属性
var bigImg = document.querySelector('#img1');
var imgs = document.querySelectorAll('#img');
for (var i = 0; i < imgs.length; i++ ) {
// 动态添加属性
imgs[i].picture = 'img/slide-' + (i + 1) + '.jpg';
imgs[i].addEventListener('mouseover', function(evt) {
img = evt.target || evt.srcElement;
bigImg.src = img.picture;
});
}
</script>
</body>
</html>
网友评论