<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>banner</title>
<style>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
.container {
width: 440px;
height: 784px;
overflow: hidden;
}
.banner {
height: 784px;
display: flex;
}
img {
width: 440px;
height: 784px;
}
</style>
</head>
<body>
<div class="container">
<div class="banner"></div>
</div>
<button class="pre">上一张</button>
<button class="next">下一张</button>
<script>
const state = {
imgList: [
'./image/7.png',
'./image/2.png',
'./image/3.png',
'./image/6.png'
],
timer: null,
curIndex: 0
}
let bannerEl = document.querySelector('.banner')
let imgListEl = null
const preBtnEl = document.querySelector('.pre')
const nextBtnEl = document.querySelector('.next')
const handlePreRoll = (e) => {
state.curIndex--
bannerEl.style.transform = `translateX(${-state.curIndex * 100}%)`
bannerEl.style.transition = 'all .5s ease'
if (state.curIndex === 0) {
setTimeout(() => {
state.curIndex = imgListEl.length - 2
bannerEl.style.transform = `translateX(${-state.curIndex * 100}%)`
bannerEl.style.transition = `none`
}, 500);
}
}
const handleNextRoll = (e) => {
state.curIndex++
bannerEl.style.transform = `translateX(-${state.curIndex * 100}%)`
bannerEl.style.transition = `all .5s ease`
if (state.curIndex === imgListEl.length - 1) {
state.curIndex = 1
setTimeout(() => {
bannerEl.style.transform = `translateX(-100%)`
bannerEl.style.transition = 'none'
}, 500);
}
}
preBtnEl.addEventListener('click', handlePreRoll)
nextBtnEl.addEventListener('click', handleNextRoll)
const init = () => {
const firstImg = state.imgList[0]
const lastImg = state.imgList[state.imgList.length - 1]
state.imgList.unshift(lastImg)
state.imgList.push(firstImg)
state.curIndex++
bannerEl.style.transform = `translateX(-${state.curIndex * 100}%)`
for (let img of state.imgList) {
const imgEl = document.createElement('img')
imgEl.src = img
bannerEl.append(imgEl)
}
startRoll()
}
const startRoll = () => {
imgListEl = bannerEl.children
}
const endRoll = () => {
clearInterval(state.timer)
state.timer = null;
}
init()
</script>
</body>
</html>