原生JavaScript实现轮播图效果

本文实例为大家分享了JavaScript实现轮播图效果的具体代码,供大家参考,具体内容如下

一、功能:

1、每隔2.5s自动切换下一张轮播图;

2、底部按钮切换对应轮播图;

3、鼠标移入暂停自动切换,移出开始;

4、鼠标移入,左右切换按钮出现,并可左右切换轮播图。

二、效果(GIF):

三、代码:

结构层(HTML)

<div class="box">
 <img src="./image/banner1.jpg" />
 <div class="arrows left">
  <img src="./image/left.png" />
 </div>
 <div class="arrows right">
  <img src="./image/right.png" />
 </div>
 <ul class="buttom"></ul>
</div>

表现层(CSS)

.box {
 width: 300px;
 height: 200px;
 background: #333;
 border-radius: 5px;
 overflow: hidden;
 margin: 0 auto;
 font-size: 0;
 position: relative;
 display: flex;
 align-items: center;
}
 
.box:hover .arrows{
 display: block;
}
 
.box img{
 width: 100%;
}
 
.arrows {
 width: 20px;
 text-align: center;
 position: absolute;
 top: 50%;
 transform: translateY(-50%);
 z-index: 9;
 font-size: 30px;
 display: none;
}
 
.left{
 left: 10px;
}
 
.right{
 right: 10px;
}
 
.buttom{
 list-style: none;
 margin: 0;
 padding: 0;
 display: flex;
 justify-content: center;
 position: absolute;
 bottom: 10px;
 left: 50%;
 transform: translateX(-50%);
}
 
.buttom li {
 width: 20px;
 height: 5px;
 border-radius: 1px;
 background: #fff;
 margin: 0 2px;
}
 
.active {
 background: red !important;
}

行为层(JavaScript)

let count = 0 // 创建当前轮播图下标
// 获取DOM元素
let box = document.querySelector('.box')
let img = document.querySelector('img')
let left = document.querySelector('.left')
let right = document.querySelector('.right')
let ul = document.querySelector('ul')
 
// 轮播图片数组
let imgArr = [
 './image/banner1.jpg',
 './image/banner2.jpg',
 './image/banner3.jpg',
 './image/banner4.jpg'
]
 
// 遍历图片数组 添加对应底部切换li标签
imgArr.forEach(() => {
 let li = document.createElement('li')
 ul.appendChild(li)
})
 
let lis = document.querySelectorAll('li') // 获取所有li标签
lis[0].className = 'active' // 给第一个li标签添加选中状态
 
// 执行切换轮播图
function switchImg (type) {
 return function() {
  if(type == 1) {
   if(count - 1 < 0) {
    count = imgArr.length - 1
   } else {
    count += -1
   }
  } else {
   if(count + 1 >= imgArr.length) {
    count = 0
   } else {
    count += 1
   }
  }
  img.src = imgArr[count]
  lis.forEach((v,i) => {
   lis[i].className = ''
   if(i == count) {
    lis[i].className = 'active'
   }
  })
 }
}
 
left.addEventListener('click', switchImg(1)) // 上一张轮播图
right.addEventListener('click', switchImg(2)) // 下一张轮播图
// 点击底部li标签切换轮播图
lis.forEach((value,index) => {
 lis[index].addEventListener('click', () => {
  lis.forEach((v,i) => {
   lis[i].className = ''
  })
  count = index
  img.src = imgArr[count]
  lis[count].className = 'active'
 })
})
// 创建定时器 每隔2.5s自动切换下一张轮播图
let swiper = setInterval(() => {
 right.click()
},2500)
// 鼠标移入暂停自动切换
box.onmouseenter = () => {
 clearInterval(swiper)
}
// 鼠标移出开始自动切换
box.onmouseleave = () => {
 swiper = setInterval(() => {
  right.click()
 },1500)
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

若文章对您有帮助,帮忙点个赞!

0
-5
发布时间 2021-09-22 12:00:30
0 条回复(回复会通过微信通知作者)
点击加载更多评论
登录 后再进行评论
(微信扫码即可登录,无需注册)