这是css的代码
.main {
width: 750px;
height: 500px;
box-sizing: border-box;
padding: 30px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
#img {
width: 100%;
height: 100%;
}
#img img {
width: 100%;
height: 100%;
}
.left {
position: relative;
left: 50px;
top: -250px;
width: 100px;
height: 100px;
}
.right {
width: 100px;
height: 100px;
position: relative;
right: -450px;
top: -250px;
}
<div class="main">
<div id="img"></div>
<div>
<img src="./img/left.png" alt="" class="left">
<img src="./img/right.png" alt="" class="right">
</div>
</div>
const imgArray = ['./img/test-6.jpg', './img/test-7.jpg', './img/test-8.jpg', './img/test-9.jpg', './img/test-10.jpg', './img/test-11.jpg', './img/test-12.jpg', './img/test-13.jpg', './img/test-14.jpg', './img/test-19.jpg', './img/test-20.jpg']
let index = 0
let maxIndex = imgArray.length - 1
let img = document.getElementById('img')
function change(index) {
if (img.childNodes.length) {
img.removeChild(img.childNodes[0])
}
let image = document.createElement('img')
image.src = imgArray[index]
img.appendChild(image)
}
change(index)
let left = document.querySelector('.left')
let right = document.querySelector('.right')
left.onclick = function () {
index--;
if (index < 0) {
index = maxIndex
}
change(index)
}
right.onclick = function () {
index++;
if (index > maxIndex) {
index = 0
}
change(index)
}
解析:左右滑动的效果主要是操作数组下标的加减,从而修改获取到的数组的值,进而实现左右滑动的效果。