哎!本来想放个视频出来的,算了,动画自己脑补吧。
触摸列表 | 说明 |
---|---|
touchstart | 手指触摸 |
touchmove | 手指移动 |
touchend | 手指离开 |
window.addEventListener('load', function () {
//首先给最左边添加最后一张图片和最右边添加第一张图片
const div = document.querySelector('div');
const ul = document.querySelector('ul');
const li = document.querySelectorAll('ul li');
const ol = document.querySelector('ol');
//给右边添加第一张图片
ul.appendChild(li[0].cloneNode(true));
//给左边添加最后一张图片
ul.insertBefore(li[li.length - 1].cloneNode(true), li[0]);
//给 ul 定义宽度
ul.style.width = document.querySelectorAll('ul li').length * 100 + '%';
//动态生成小圆点的个数
for (let i = 0, length = document.querySelectorAll('ul li').length - 2; i < length; i++) {
let li = document.createElement('li');
ol.appendChild(li);
}
//图片索引
let index = 0;
//图片的宽度
let imageWidth = li[0].offsetWidth;
//与图片索引对应的小圆点
ol.children[index].classList.add('current');
//设置定时器
let time = setInterval(function () {
index++;
ul.style.transition = "all 0.3s";
ul.style.transform = `translateX(${-index * imageWidth}px)`;
}, 2000)
//当过渡完成之后,再去判断 实现无缝滚动
ul.addEventListener('transitionend', function () {
//当index 大于等于图片的长度时 立即回到第一张图片
if (index >= li.length) {
index = 0;
ul.style.transition = "none";
ul.style.transform = `translateX(${-index * imageWidth}px)`;
} else if (index < 0) { ///当index 小于图片长度时 立即回到最后一张图片
index = li.length - 1;
ul.style.transition = "none";
ul.style.transform = `translateX(${-index * imageWidth}px)`;
}
//为小圆点添加样式
ol.querySelector(".current").classList.remove('current');
ol.children[index].classList.add('current');
})
let startX = 0; //手指初始的距离
let moveX = 0; //手指移动的距离
//手指触摸
ul.addEventListener('touchstart', function (e) {
clearInterval(time);
startX = e.targetTouches[0].pageX;
})
//手指移动
ul.addEventListener('touchmove', function (e) {
moveX = e.targetTouches[0].pageX - startX;
ul.style.transition = "none";
ul.style.transform = `translateX(${-index * imageWidth + moveX}px)`;
})
//手指离开
ul.addEventListener('touchend', function (e) {
if (Math.abs(moveX) > 50) {
if (moveX > 0) {
index--;
} else if (moveX < 0) {
index++;
}
} else { //回弹效果
ul.style.transition = "all 0.1s";
ul.style.transform = `translateX(${-index * imageWidth}px)`;
}
ul.style.transition = "all 0.3s";
ul.style.transform = `translateX(${-index * imageWidth}px)`;
})
})
<div class="swiper">
<ul>
<li><img src="./image/timg (1).jpg" alt=""></li>
<li><img src="./image/timg (3).jpg" alt=""></li>
<li><img src="./image/timg4).jpg" alt=""></li>
</ul>
<ol>
</ol>
</div>
* {
margin: 0;
padding: 0;
}
.swiper {
position: relative;
overflow: hidden;
}
ul {
height: 200px;
margin-left: -100%;
}
ul li {
list-style: none;
float: left;
width: 100vw;
height: 100%;
}
li img {
width: 100%;
height: 100%;
}
ol {
position: absolute;
right: 10px;
bottom: 0;
z-index: 99;
}
ol li {
margin: 5px;
padding: 5px;
border-radius: 10px;
background-color: white;
float: left;
list-style: none;
transition: all 0.1s;
}
.current {
width: 15px;
}