1. 程式人生 > 程式設計 >原生JavaScript實現輪播圖效果

原生JavaScript實現輪播圖效果

本文例項為大家分享了Scrihttp://www.cppcns.compt實現輪播圖效果的具體程式碼,供大家參考,具體內容如下

一、功能:

1、每隔2.5s自動切換下一張輪播圖;

2、底部按鈕切換對應輪播圖;

3、滑鼠移入暫停自動切換,移出開始;

4、滑鼠移入,左右切換按鈕出現,並可左右切換輪播圖。

二、效果(GIF):

原生JavaScript實現輪播圖效果

三、程式碼:

結構層(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>

表現層()

.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; }

行為層()

let count = 0 // 建立當前輪播圖下標
// 獲取DOM元素
let box = document.querySelector('.box')
let ARmBwyoimg = 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)
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。