You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
lunbotu/自动轮播图.html

153 lines
4.2 KiB

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>111</title>
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 1000px;
height: 500px;
/* overflow: hidden; */
position: relative;
margin: 0 auto;
text-align: center;
background-color: aqua;
}
img {
width: 90%;
height: 90%;
}
.left {
position: absolute;
background-color: #666;
width: 30px;
height: 40px;
color: #fff;
text-align: center;
line-height: 40px;
top: 45%;
left: 5px;
cursor: pointer;
}
.right {
position: absolute;
background-color: #666;
width: 30px;
height: 40px;
color: #fff;
text-align: center;
line-height: 40px;
top: 45%;
right: 5px;
cursor: pointer;
}
.slider-indictor {
position: absolute;
bottom: 15px;
left: 50%;
list-style: none;
display: flex;
}
.slider-indictor li {
width: 8px;
height: 8px;
margin: 4px;
border-radius: 50%;
background: #fff;
opacity: 0.4;
cursor: pointer;
}
.slider-indictor li.active {
width: 12px;
height: 12px;
opacity: 1;
}
</style>
</head>
<body>
<div class="box">
<img src="./img/1.jpg" alt="">
<div class="left"><</div>
<div class="right">></div>
<ul class="slider-indictor">
<li class="active"></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
</body>
<script>
//定义图片数组
const imgs = ['./img/1.jpg', './img/2.jpg', './img/3.jpg', './img/4.jpg']
//获取img元素
const img = document.querySelector('img')
const left = document.querySelector('.left')
const right = document.querySelector('.right')
let i = 0
let n= setInterval(() => {
i++
if (i > imgs.length - 1) {
i = 0
}
img.src = imgs[i]
document.querySelector('.slider-indictor .active').classList.remove('active')
document.querySelector(`.slider-indictor li:nth-child(${i + 1})`).classList.add('active')
}, 1000)
//鼠标经过关闭定时器
const box=document.querySelector('.box')
box.addEventListener('mouseenter',function(){
clearInterval(n)
})
//鼠标离开开启定时器
box.addEventListener('mouseleave',function(){
clearInterval(n)
//开启定时器
n= setInterval(() => {
i++
if (i > imgs.length - 1) {
i = 0
}
img.src = imgs[i]
document.querySelector('.slider-indictor .active').classList.remove('active')
document.querySelector(`.slider-indictor li:nth-child(${i + 1})`).classList.add('active')
}, 1000)
})
left.addEventListener('click',function(){
i--
if(i<0){
i=3
}
img.src=imgs[i]
document.querySelector('.slider-indictor .active').classList.remove('active')
document.querySelector(`.slider-indictor li:nth-child(${i + 1})`).classList.add('active')
})
right.addEventListener('click',function(){
i++
if(i>=imgs.length){
i=0
}
img.src=imgs[i]
document.querySelector('.slider-indictor .active').classList.remove('active')
document.querySelector(`.slider-indictor li:nth-child(${i + 1})`).classList.add('active')
})
</script>
</html>