页面布局
设置一个父容器作为遮罩,子容器包含了要播放的图片
子容器为flex布局使元素水平排列
子容器中的图片元素flex-shrink:0
确保元素不被压缩
通过改变子容器的left实现轮播图的移动
原理
- 首先在图片的首和尾使用
insertBefore
appendChild
cloneNode
方法将首尾的- 图片克隆添加到首尾 - 然后将父元素 left 向左移动一个屏幕宽度的距离。这样才能让第二张(因为首尾各添加了一张图片,所以原先的第一张就变成了第二张)变成可视范围的第一张
- 通过为元素添加和清除
transition:left 0.5s linear
属性实现首尾无缝切换 - 其目的是播放最后一张的同时,与第一张偷梁换柱。因为最后一张与第一张图片相同,所以快速地改变其 left 用户并无感知
代码
<!DOCTYPE html>
<html>
<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>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="swiper">
<div class="slider">
<img src="https://img.alicdn.com/imgextra/i4/6000000005291/O1CN01mr9XQt1oxKHmEckLQ_!!6000000005291-0-octopus.jpg" alt="">
<img src="https://gtms03.alicdn.com/tps/i3/TB1gXd1JXXXXXapXpXXvKyzTVXX-520-280.jpg" alt="">
<img src="https://gtms01.alicdn.com/tps/i1/TB1r4h8JXXXXXXoXXXXvKyzTVXX-520-280.jpg" alt="">
<img src="https://gtms02.alicdn.com/tps/i2/TB10vPXKpXXXXacXXXXvKyzTVXX-520-280.jpg" alt="">
</div>
<div class="control" id="left"><</div>
<div class="control" id="right">></div>
</div>
<script>
var currentIndex = 1;
var slider = document.getElementsByClassName('slider')[0];
function left(){
if(currentIndex === 0){
slider.style.left = 4*(-520) + 'px';
slider.style.transition = 'left 0s';
currentIndex = 4;
setTimeout(() => {
currentIndex--;
play(currentIndex);
}, 1);
}else{
currentIndex--;
play(currentIndex);
}
}
function right(){
if(currentIndex === 5){
slider.style.left = 1*(-520) + 'px';
slider.style.transition = 'left 0s';
currentIndex = 1;
setTimeout(() => {
currentIndex++;
play(currentIndex);
}, 1);
}else{
currentIndex++;
play(currentIndex);
}
}
function play(index){
slider.style.left = index*(-520) + 'px';
slider.style.transition = 'left 0.5s linear';
console.log(currentIndex)
}
(function initSwiper(){
var firstImg = slider.firstElementChild.cloneNode(true);
var lastImg = slider.lastElementChild.cloneNode(true);
slider.appendChild(firstImg);
slider.insertBefore(lastImg,document.getElementsByTagName('img')[0])
slider.style.left = '-520px';
document.getElementById('left').addEventListener('click',left);
document.getElementById('right').addEventListener('click',right);
play(1);
})();
function autoPlay(){
setInterval(() => {
right()
}, 1200);
}
autoPlay();
</script>
</body>
</html>
*{
padding: 0;
margin: 0;
box-sizing: content-box;
}
.swiper{
width: 520px;
height: 280px;
margin: 20px auto;
border-radius: 10px;
border: 2px solid green;
position: relative;
overflow: hidden;
}
.slider{
width: 100%;
height: auto;
display: flex;
position: relative;
}
.slider > img{
display: block;
width: 100%;
flex-shrink: 0;
}
.control{
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 30px;
text-align: center;
height: 50px;
background-color: rgba(160,160,160,0.8);
font-size: 30px;
font-weight: bold;
line-height: 50px;
color: white;
}
.control:nth-child(3){
right: 0;
}