轮播图JS实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>轮播图</title>
<style>
.box{
width: 500px;
height: 300px;
position: relative;
margin: 100px auto;
}
img{
width: 500px;
height: 300px;
/*隐藏图片*/
display: none;
position: absolute;
/*给图片所有的图片添加定位*/
left: 0;
top: 0;
/* box-sizing: 3; */
}
.bor{/*上按钮*/
position: absolute;
left: 0;
top: 50%;
width: 50px;
height: 50px;
background-color: rgba(0, 0, 0, .03);
color: #ffffff;
font-weight: bolder;
font-size: 30px;
text-align: center;
line-height: 50px;
}
.next{/*下按钮*/
position: absolute;
right: 0;
top: 50%;
text-align: center;
line-height: 50px;
width: 50px;
height: 50px;
background-color: rgba(0, 0, 0, .03);
color: #ffffff;
font-weight: bolder;
font-size: 30px;
}
.f{/*显示图片*/
display: block;
}
.button{
width: 300px;
height: 20px;
position: absolute;
left: 330px;
top: 370px;
background-color: rgba(0, 0, 0, .1);
border-radius: 20px;
/* box-sizing: border-box; */
display: flex;
justify-content: space-around;
align-items: center;
}
.button span{
background-color: rgba(0, 0, 0, .5);
width: 15px;
height: 15px;
border-radius: 50%;
}
.button .c{
background-color: #fff;
}
</style>
</head>
<body>
<div class="box">
<!-- <img src="./img/1.jpg" alt="" class="f">
<img src="./img/2.jpg" alt="">
<img src="./img/3.jpg" alt=""> -->
</div>
<div class="button">
</div>
<script>
let box=document.querySelector('.box')
let arr=['./img/1.jpg','./img/2.jpg','./img/3.jpg','./img/1.jpg','./img/2.jpg','./img/3.jpg']
let bun=document.querySelector('.button')
let index=0
arr.map((item,index)=>{
box.innerHTML+=`<img src="${item}" alt="">`
bun.innerHTML+=`<span></span>`
})//动态渲染
//可以动态渲染图片也可以使用标签实现
box.innerHTML+=`<div class="next">〉</div>
<div class="bor">〈</div>
`//按钮必须在图片后面
let img=[...document.querySelectorAll('img')]
let prve=document.querySelector('.bor')
let next=document.querySelector('.next')
let sp=[...document.querySelectorAll('span')]
img[0].className='f'//默认显示第一个图片
sp[0].className='c'
setInterval(()=>{
carousel('next')//控制方向
},3000)
next.addEventListener('click',()=>{
carousel('next')//向下
})
prve.addEventListener('click',()=>{
carousel('prve')//向上
})
sp.forEach((item,index)=>{
item.addEventListener('click',()=>{
carousel(index)
})
})
function carousel (direction){
img[index].style.display='none'//在改变之前让上一张图片隐藏
sp[index].style.backgroundColor='rgba(0, 0, 0, .3)'
if(direction=='next'){ //判断点击的是下一张图片
//向下
index++
index=index>=img.length?0:index//边界判断
}else if(direction=='prve'){//点击的是上一张图片
index--//向上
index=index<=0?img.length-1:index//边界判断
// console.log(index);
}else{//点击的是要跳转的下标
index=direction
}
img[index].style.display='block'//改变之后的状态显示
sp[index].style.backgroundColor='#fff'
}
</script>
</body>
</html>
感觉有帮助的麻烦给点个赞