<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>serInterval_轮播图</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
#outer{
width: 100vw;
position: relative;
}
img{
width: 100%;
}
span{
position: absolute;
bottom: 50%;
color: #f00;
display: block;
font-size: 24px;
cursor: pointer;
z-index: 9;
}
.btn1{
left: 30px;
}
.btn2{
right: 30px;
}
#tag{
width: 140px;
height: 10px;
position: absolute;
left: 50%;
margin-left: -70px;
bottom: 20px;
display: flex;
/* flex-direction:column-reverse;/*改变方向 */
justify-content:space-between;
}
#tag i{
box-sizing: border-box;
width: 10px;
text-align: center;
border-radius: 10px;
cursor: pointer;
background-color: rgba(255,0,0,.2);
}
</style>
</head>
<body>
<div id="outer">
<img src="../DOM/img/01.png" >
<span class="btn1" id="btn1" type="button"><</span>
<span class="btn2" id="btn2" type="button">></span>
<div id="tag">
<i></i>
<i></i>
<i></i>
<i></i>
<i></i>
<i></i>
</div>
</div>
<script>
window.onload = function(){
let urls = [
"../DOM/img/01.png",
"../DOM/img/02.jpg",
"../DOM/img/03.png",
"../DOM/img/04.jpg",
"../DOM/img/05.jpg",
"../DOM/img/06.png",
];
let key = 0;
let btn1 = document.getElementById("btn1");
let btn2 = document.getElementById("btn2");
let img = document.getElementsByTagName("img")[0];
let tag = document.getElementById("tag");
let i = tag.getElementsByTagName("i");
let item = i[key].style.backgroundColor = "rgba(255,0,0,.8)";
//下一张
function next(){
if(key == urls.length - 1){
key = 0;
}else{
key++;
}
img.src = urls[key];
for(var k = 0 ; k < i.length ; k++){
if(k === key){
i[k].style.backgroundColor = "rgba(255,0,0, .8)";
}else{
i[k].style.backgroundColor = "rgba(255,0,0,.2)";
}
}
};
//上一张
function prev(){
if(key == 0){
key = urls.length - 1;
}else{
key--;
}
img.src = urls[key];
for(var k = 0 ; k < i.length ; k++){
if(k === key){
i[k].style.backgroundColor = "rgba(255,0,0,.8)";
}else{
i[k].style.backgroundColor = "rgba(255,0,0.2)";
}
}
};
//定时下一张
var timer = setInterval(()=>{next()},3000);
//上一张 点击暂停自动轮播
btn1.onclick = function(){
clearInterval(timer);
prev();
};
//鼠标移出开启自动轮播
btn1.onmouseout = function(){
timer = setInterval(()=>{next()},3000);
};
//下一张 点击暂停自动轮播
btn2.onclick = function(){
clearInterval(timer);
next();
};
//鼠标移出开启自动轮播
btn2.onmouseout = function(){
timer = setInterval(()=>{next()},3000);
};
}
</script>
</body>
</html>