轮播图案例
案例视图

案例用到的核心知识
- 获取 DOM 对象
- 数组
- 鼠标进入和进出事件
- 使用 JS 对样式进行操作
- for 循环
- if 判断语句
- 逻辑运算符
- 三元运算符
- 自增和自减运算符
案例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
.container {
width: 100%;
height: 520px;
position: relative;
}
img {
width: 100%;
}
.indicator {
position: absolute;
bottom: 5px;
left: 50%;
transform: translateX(-50%);
}
.indicator-item {
height: 5px;
width: 80px;
background: white;
float: left;
margin-right: 5px;
}
.pre,
.next {
width: 50px;
height: 50px;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
.pre {
left: 50px;
}
.next {
right: 50px;
}
</style>
</head>
<body>
<div class="container">
<img src="./img/1.jpg" alt="" id="img" />
<div class="indicator">
<div class="indicator-item"></div>
<div class="indicator-item"></div>
<div class="indicator-item"></div>
<div class="indicator-item"></div>
</div>
<img src="./img/pre.svg" alt="" class="pre" onclick="pre()" />
<img src="./img/next.svg" alt="" class="next" onclick="next()" />
</div>
</body>
<script>
var img = document.getElementById("img");
var container = document.getElementsByClassName("container")[0];
var indicatorItem = document.getElementsByClassName("indicator-item");
var imgArr = ["./img/1.jpg", "./img/2.jpg", "./img/3.jpg", "./img/4.jpg"];
var timer = null;
var currentIndex = 0;
indicatorItem[0].style.background = "red";
container.onmouseover = function () {
clearInterval(timer);
};
container.onmouseout = function () {
aotoPlay();
};
for (var i = 0; i < indicatorItem.length; i++) {
indicatorItem[i].index = i;
indicatorItem[i].onmouseover = function () {
img.src = imgArr[this.index];
changeIndicatorColor(this.index);
};
}
function pre() {
currentIndex--;
if (currentIndex < 0) {
currentIndex = imgArr.length - 1;
}
img.src = imgArr[currentIndex];
changeIndicatorColor();
}
function next() {
currentIndex++;
if (currentIndex >= imgArr.length) {
currentIndex = 0;
}
img.src = imgArr[currentIndex];
changeIndicatorColor();
}
function aotoPlay() {
timer = setInterval(function () {
currentIndex++;
if (currentIndex >= imgArr.length) {
currentIndex = 0;
}
img.src = imgArr[currentIndex];
changeIndicatorColor();
}, 2000);
}
function changeIndicatorColor(index) {
for (var i = 0; i < indicatorItem.length; i++) {
indicatorItem[i].style.background =
(index || currentIndex) == i ? "red" : "white";
}
}
aotoPlay();
</script>
</html>