基于html、js实现网页中常见的轮播图
html:
<div id="box">
<img src="./images/1.jpg" alt="">
<img src="./images/2.jpg" alt="">
<img src="./images/3.jpg" alt="">
<img src="./images/4.jpg" alt="">
<img src="./images/5.jpg" alt="">
<img src="images/6.jpg" alt="" />
<img src="images/7.jpg" alt="" />
<img src="images/8.jpg" alt="" />
<div class="con" id="left"><</div>
<div class="con" id="right">></div>
<ul id="list">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
css:
<style>
#box{
width: 700px;
height: 400px;
margin: 0 auto;
position: relative;
}
#box img{
position: absolute;
width: 100%;
height: 100%;
}
.con{
width: 50px;
height: 100px;
background:palegreen;
position: absolute;
top: calc(50% - 50px);
line-height: 100px;
font-size: 60px;
text-align: center;
}
.con:nth-of-type(2){
right:0
}
ul,li{
margin: 0;
padding: 0;
list-style: none;
}
#list{
position: absolute;
display:flex;
bottom: 10px;
left: calc(45% - 100px);
}
#list li{
width: 20px;
height: 20px;
background:#fff;
margin: 0 10px;
border-radius: 50%;
}
.active{
background:red !important;
}
</style>
js:
<script>
var box = document.getElementById("box")
var img = document.getElementsByTagName("img")
var list = document.getElementById("list")
var con = list.getElementsByTagName("li")
var left = document.getElementById("left")
var right = document.getElementById("right")
var index = 0;
var Inter;
function goto(){
index = index % img.length;
for(var i = 0;i<img.length;i++){
img[i].style.display = "none"
con[i].index = i
con[i].className=""
}
img[index].style.display="block"
con[index].className="active"
}//程序主函数
settime()
function settime(){
Inter = setInterval(()=>{
goto()
index++;
},1000)
}//自动轮播
left.addEventListener("click",()=>{
index--
if(index<0){
index = img.length - 1
}
goto()
})
right.addEventListener("click",()=>{
index++
if(index>img.length-1){
index=0
}
goto()
})//左右按钮切换实现
list.addEventListener("click",(e)=>{
index = e.target.index
console.log(index);
goto()
})//点击图标切换实现
box.addEventListener("mouseover",()=>{
clearInterval(Inter)
})
box.addEventListener("mouseout",()=>{
settime()
})//鼠标移入移出实现
</script>
实现效果