JS学习有一段时间了,还是没有能够很好理解广告轮播的思想,在学习其他代码后,经过一番功夫,写了一个轮播。个人笔记,如有错误,请指正。
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>广告轮播</title>
<style>
/*公共样式*/
* {
margin: 0;
padding: 0;
}
ul, ol, li {
list-style: none;
}
a {
text-decoration: none;;
}
/*自定义样式*/
.wrap {
width: 780px;
height: 300px;
margin: 20px auto;
position: relative;
overflow: hidden;
}
.wrap .wrap-box {
width: 3900px;
position: absolute;
}
.wrap .wrap-box li {
width: 780px;
height: 300px;
float: left;
}
.wrap .wrap-box img {
display: block;
width: 100%;
height: 300px;
}
.wrap .btn-list {
position: absolute;
top: 90%;
left: 50%;
transform: translateX(-50%);
}
.wrap .btn-list li {
width: 15px;
height: 15px;
float: left;
margin-right: 10px;
border-radius: 50%;
background: #fff;
opacity: .3;
cursor: pointer;
}
.wrap .btn-list li.active {
opacity: .9;
}
</style>
</head>
<body>
<!--外层父容器-->
<div class="wrap" id="wrap">
<!--图片容器-->
<ul class="wrap-box" id="wrap-box">
<li><a href="#"><img src="http://pic1.win4000.com/wallpaper/1/584a2378ab355.jpg" alt=""/></a></li>
<li><a href="#"><img src="http://www.pp3.cn/uploads/201510/2015101503.jpg" alt=""/></a></li>
<li><a href="#"><img src="http://pic1.win4000.com/wallpaper/2/57982729785df.jpg" alt=""/></a></li>
<li><a href="#"><img src="http://pic1.win4000.com/wallpaper/7/56efc26bd5529.jpg" alt=""/></a></li>
<li><a href="#"><img src="http://www.pp3.cn/uploads/201608/2016082012.jpg" alt=""/></a></li>
</ul>
<!--图片对应按钮-->
<ul class="btn-list" id="btn-list">
<li class="active"></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
<script>
window.onload = function () {
//获取需要操作的元素,声明变量
var wrap = document.getElementById('wrap'),
wrapBox = document.getElementById('wrap-box'),
liBtn = document.querySelectorAll('#btn-list li'),
index = 0,
timer = null;
//定义并调用自动轮播函数
if (timer) {
//停止自动轮播
clearInterval(timer);
timer = null;
}
timer = setInterval(autoplay, 3000);
//定义图片切换函数
function autoplay() {
index++;
if (index >= liBtn.length) {
index = 0;
}
changeImg(index);
}
function changeImg(curIndex) {
for (var i = 0; i < liBtn.length; i++) {
liBtn[i].className = '';
wrapBox.style.left = 0;
}
liBtn[curIndex].className = 'active';
wrapBox.style.left = -curIndex * 780 + 'px';
index = curIndex;
}
//鼠标进入清除定时器
wrap.onmouseover = function () {
clearInterval(timer);
}
//鼠标移出后启动轮播
wrap.onmouseout = function () {
timer = setInterval(autoplay, 3000);
}
//鼠标移动到小圆点时显示对应的图片
for (var j = 0; j < liBtn.length; j++) {
liBtn[j].order = j;
liBtn[j].onmouseover = function () {
clearInterval(timer);
changeImg(this.order);
}
}
}
</script>
</body>
</html>
效果图如下:
![]()