赞
踩
改造之前的纯手动切换,现在加入自动轮播,鼠标移到图片上停止播放,可以实现手动切换,当鼠标离开图片上后自动轮播
必要的css,html
参照前面文章给的css,html
业务逻辑修改
window.onload = function () {
const oPic = document.getElementById('pic')
const oImg = oPic.querySelector('#pic img')
const oUl = document.querySelector('#pic ul')
const oLi = oUl.querySelectorAll('#pic ul li')
const oSpan = document.querySelector('#pic span')
const oP = document.querySelector('#pic p')
const arrUrl = [
'./images/img1.png',
'./images/img2.png',
'./images/img3.png',
'./images/img4.png'
]
const arrText = [
'这是第一张图片',
'这是第二张图片',
'这是第三张图片',
'这是第四张图片'
]
//初始化
let num = 0
let timer = null
init()
function init() {
oImg.src = arrUrl[num]
oSpan.innerHTML = `数量:${num + 1} / 4`
oP.innerHTML = arrText[num]
for (var i = 0; i < oLi.length; i++) {
oLi[i].classList.remove('active')
}
oLi[num].classList.add('active')
}
setTimeout(autoPlay,2000)
tab()
//点击切换图片
function tab() {
for (var i = 0; i < oLi.length; i++) {
oLi[i].index = i
oLi[i].onclick = function () {
num = this.index
init()
for (var i = 0; i < oLi.length; i++) {
oLi[i].classList.remove('active')
}
this.classList.add('active')
}
}
}
//鼠标经过停止轮播
oPic.onmouseover = function () {
clearInterval(timer)
}
//鼠标离开继续轮播
oPic.onmouseout = function () {
autoPlay()
}
//自动轮播
function autoPlay() {
clearInterval(timer)
timer = setInterval(function () {
num++
num %= 4
init()
}, 1000)
}
}
可以对照着试试
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。