上代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
#oImg{
width: 500px;
height: 300px;
background-size: 500px 300px;
position: relative;
margin: 100px auto;
}
#btn-previous{
width: 30px;
position: absolute;
left: 25px;
top:150px;
}
#btn-next{
width: 30px;
position: absolute;
left: 450px;
top:150px;
}
li{
list-style: none;
width: 10px;
height: 10px;
background: black;
border-radius: 50%;
margin: 10px;
float: left;
}
ul{
position: absolute;
left: 120px;
top:250px;
}
</style>
</head>
<body>
<div id = "oImg">
<input id="btn-previous" type="button" value="<"/>
<input id="btn-next" type="button" value=">"/>
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
</body>
</html>
<script>
class Banner{
constructor(newImg,newLi){ //传入需要改变的 图片和小圆点
this.index = 0; //初始索引是0
this.oImg = newImg; //初始化图片
this.oLi = newLi; //初始化小圆点
this.time=0; //定时器初始值
this.oImg.style.backgroundImage = "url(img/"+this.index+".jpg)";//设置图片绑定索引
this.oLi[this.index].style.backgroundColor = "red"; //设置小圆点的样式
}
//设置Div的背景图片
setImgBackground(){
this.oImg.style.backgroundImage = "url(img/"+this.index+".jpg)";
}
//设置li的颜色
setOligBackgroundColor(){
for(let i=0; i<this.oLi.length; i++){//遍历小圆点
if(i == this.index){ //如果点击了当前li
this.oLi[i].style.backgroundColor = "red";//小圆点背景变成了红色
}else{
this.oLi[i].style.backgroundColor = "black"; //否则就变回黑色
}
}
}
prev(){
this.index--; //创建一个函数向左的
if(this.index == -1){ //如果当前索引是-1
this.index = this.oLi.length-1; // 把-1变成最后一张图片实现轮播的效果
}
this.setImgBackground(); //调用方法
this.setOligBackgroundColor();
}
next(){
this.index++; //创建函数向右的
if(this.index == this.oLi.length){ //如果当前图片是最后一张,让当前图片变成第一张
this.index = 0;
}
this.setImgBackground(); //调用方法
this.setOligBackgroundColor();
}
play(){ //创建定时器
let that=this;
this.time=setInterval(function(){
that.next();
},2000)
}
eventBind(){ //创建按钮函数
let oPrev = document.getElementById("btn-previous");//获取向左和向右的按钮
let oNext = document.getElementById("btn-next");
let that = this;
oPrev.onclick = function(){ //点击左按钮的时候调用prev函数
that.prev();
}
oNext.onclick = function(){ //点击右按钮的时候调用next函数
that.next();
}
//调用定时器
this.play();
this.oImg.onmouseover=function(){ //鼠标滑过清除定时器
clearInterval(that.time);
}
this.oImg.onmouseout=function(){ //鼠标移开调用
clearInterval(that.time);
that.play();
}
}
eventBindLi(){ //创建li函数
let that = this;
for(let i=0; i<this.oLi.length; i++){ //遍历所有的li
this.oLi[i].onclick = function(){ //绑定事件函数 点击第几个li的时候调用函数
that.index = i; //当前点击的索引
that.setImgBackground();
that.setOligBackgroundColor();
}
}
}
}
let oImg = document.querySelector("#oImg"); //获取图片和li
let oLi = document.getElementsByTagName("li");
let b = new Banner(oImg,oLi); //传入参数
b.eventBind(); //调用创建的左右箭头按钮和li按钮
b.eventBindLi();
</script>