<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
* {
padding: 0;
margin: 0;
}
#oImg {
width: 800px;
height: 500px;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
background: url(img/q0.png) no-repeat;
background-size: 800px 500px;
}
ul {
list-style: none;
position: absolute;
margin-top: 450px;
margin-left: 280px;
}
li {
width: 20px;
height: 20px;
background: white;
border-radius: 50%;
float: left;
margin: 0 20px;
}
button {
width: 50px;
height: 50px;
font-size: 50px;
border: 0;
background: white;
}
#btn1 {
float: left;
margin-top: 200px;
}
#btn2 {
margin-top: 200px;
float: right;
}
</style>
</head>
<body>
<div id="oImg">
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<button type="button" id="btn1"><</button>
<button type="button" id="btn2">></button>
</div>
</body>
</html>
<script type="text/javascript">
class Slideshow{
constructor(newImg,newLi,newOimg) {
this.img = newImg;
this.oLi = newLi;
this.oImg = newOimg;
this.index = 0;
this.oLi[this.index].style.background = "red";
this.oImg.style.background="url(img/q"+this.index+".png)";
}
//设置li的背景颜色
setLiColor(){
for(let i=0; i<this.oLi.length; i++){
if(i == this.index){
this.oLi[i].style.background = "red";
}else{
this.oLi[i].style.background = "black";
}
}
}
//设置div的背景图片
setOimgBackGround(){
this.oImg.style.background="url(img/q"+this.index+".png)"+"100%"+"100%";
}
//下一张图
nextImg(){
this.index++;
if(this.index == this.oLi.length){
this.index=0
}
this.setLiColor();
this.setOimgBackGround();
}
//上一张图
previousImg(){
this.index--;
if(this.index == -1){
this.index = 3;
}
this.setLiColor();
this.setOimgBackGround();
}
eventBindBtn(){
let btn1 = document.getElementById("btn1");
let btn2 = document.getElementById("btn2");
let that = this;
btn1.onclick=function(){
that.previousImg();
}
btn2.onclick=function(){
that.nextImg();
}
}
eventBindLi(){
for(let i=0; i<this.oLi.length; i++){
let that = this;
this.oLi[i].onclick=function(){
that.index = i;
that.setLiColor();
that.setOimgBackGround();
}
}
}
}
let Oli = document.getElementsByTagName("li");
let oImg = document.getElementById("oImg");
let sl = new Slideshow(["q0.png","q1.png","q2","q3.png"],Oli,oImg);
sl.eventBindBtn();
sl.eventBindLi();
</script>
js实现轮播图
最新推荐文章于 2024-04-09 17:12:14 发布