html页面如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="./carousel.css">
<script src="./carousel.js"></script>
<title>轮播</title>
</head>
<body>
<div id="box">
<img id="pic" src="./img/1.jpg" alt="">
<ul id="list">
<li>1</li>
<li>2</li>
</ul>
<div class="btn" id="left"><</div>
<div class="btn" id="right">></div>
</div>
</body>
</html>
CSS文件
*{
margin: 0;
padding: 0;
}
#box{
width: 790px;
height: 340px;
margin: 0 auto;
position: relative;
}
.btn{
width: 50px;
height: 100px;
color: #fff;
background-color: rgba(0,0,0,0.2);
font-size: 40px;
text-align: center;
line-height: 100px;
position: absolute;
top: 120px;
display: none;
}
#left{
left: 0px;
}
#right{
right: 0px;
}
ul {
list-style: none;
position: absolute;
bottom: 20px;
left: 230px;
}
ul li{
float: left;
width: 20px;
height: 20px;
margin-left: 10px;
background-color: #aaa;
text-align: center;
line-height: 20px;
border-radius: 50%;
}
JS文件
window.onload = function() {
var box = document.getElementById("box");
var img = document.getElementById("pic");
var left_btn = document.getElementById("left");
var right_btn = document.getElementById("right");
var allLi = document.getElementsByTagName("li");
//第一步 :第一个按钮设置为红色
var currentNUM = 1;
allLi[0].style.backgroundColor = "red";
var timer = setInterval(startloop,2000);
function startloop(){
currentNUM++;
changeImg()
}
function changeImg(){
if(currentNUM==0){
currentNUM = 2;
}else if(currentNUM == 3){
currentNUM = 1;
}
img.src = "img/" + currentNUM + '.jpg';
for(let i=0;i<allLi.length;i++){
allLi[i].style.backgroundColor = "#aaa";
}
allLi[currentNUM-1].style.backgroundColor = 'red';
}
box.addEventListener('mouseover',function(){
left_btn.style.display = 'block';
right_btn.style.display = 'block';
window.clearInterval(timer)
})
box.addEventListener('mouseout',function(){
left_btn.style.display = 'none';
right_btn.style.display = 'none';
timer = setInterval(startloop,2000)
})
left_btn.addEventListener('mouseover',deep);
left_btn.addEventListener('mouseout',undeep);
right_btn.addEventListener('mouseover',deep);
right_btn.addEventListener('mouseout',undeep);
left_btn.addEventListener('click',function(){
currentNUM--;
changeImg();
})
right_btn.addEventListener('click',startloop);
function deep(){
this.style.backgroundColor = "rgba(0,0,0,0.4)"
}
function undeep(){
this.style.backgroundColor = "rgba(0,0,0,0.2)"
}
for(let i=0;i<allLi.length;i++){
allLi[i].index = i+1
allLi[i].addEventListener('mouseover',function(){
// allLi[0]
currentNUM = this.index
changeImg();
})
}
}