<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
ul,
li {
list-style: none;
margin: 0;
padding: 0;
}
#box {
width: 800px;
height: 400px;
border: 1px solid black;
margin: 100px auto;
position: relative;
}
.list,
.list li {
width: 100%;
height: 100%;
}
.list li {
display: none;
}
.btns {
width: 100%;
height: 80px;
position: absolute;
top: 50%;
transform: translateY(-50%);
display: flex;
justify-content: space-between;
}
.btns .left,
.btns .right {
width: 50px;
height: 80px;
background: powderblue;
text-align: center;
line-height: 80px;
text-decoration: none;
color: black;
font-size: 30px;
}
.navs {
width: 100%;
height: 30px;
position: absolute;
bottom: 5px;
display: flex;
justify-content: center;
}
.navs span {
width: 30px;
height: 30px;
background: green;
text-align: center;
line-height: 30px;
margin: 0px 6px;
color: #fff;
font-weight: #fff;
}
.navs span:hover {
cursor: pointer;
}
</style>
</head>
<body>
<div id="box">
<!-- 图片列表 -->
<ul class="list">
<li style="display: block;"><img src="./images/1.jpeg" alt="" width="100%" height="100%"></li>
<li><img src="./images/2.jpeg" alt="" width="100%" height="100%"></li>
<li><img src="./images/3.jpeg" alt="" width="100%" height="100%"></li>
<li><img src="./images/4.jpeg" alt="" width="100%" height="100%"></li>
<li><img src="./images/5.jpg" alt="" width="100%" height="100%"></li>
</ul>
<!-- 左右按钮 -->
<div class="btns">
<a href="javascript:void(0)" class="left"> < </a>
<a href="javascript:void(0)" class="right"> > </a>
</div>
<!-- 数字列表 -->
<div class="navs">
<span style="background: red;">1</span>
<span>2</span>
<span>3</span>
<span>4</span>
<span>5</span>
</div>
</div>
<script>
// 获取到元素对象
var list = document.querySelectorAll('.list li')
var box = document.querySelector('#box')
var left = document.querySelector('.left')
var right = document.querySelector('.right')
var spans = document.querySelectorAll('.navs span')
// 定义index变量,表示当前显示图片的下标
var index = 0
var time; // 用于接收定时器
// 定义一个定时器,让图片自动轮播切换
run()
function run () {
time = setInterval(function () { toggle(1) }, 2000)
}
// 右边按钮点击
right.onclick = function () { toggle(1) }
// 左边按钮点击
left.onclick = function () { toggle(-1) }
// 给所有数字导航添加一个点击事件
for (var i = 0; i < spans.length; i++) {
spans[i].num = i
spans[i].onclick = function () {
// 给index重新赋值
index = this.num
toggle(0)
}
}
// 图片切换封装; type为-1表示减减,为1就加加
function toggle (type) {
// 每次进入时,先隐藏所有元素
for (var i = 0; i < list.length; i++) {
list[i].style.display = 'none'
spans[i].style.background = 'green'
}
index += type
if (index < 0) {
index = list.length - 1
} else {
index %= list.length
}
// 显示下一张图片
list[index].style.display = 'block'
spans[index].style.background = 'red'
}
// 给box添加一个移入事件(移入停止轮播)
box.onmouseover = function () {
clearInterval(time)
console.log('2行')
}
// 给box添加一个移出事件(移出开始轮播)
box.onmouseout = function () {
run()
console.log('不行')
}
</script>
</body>
</html>