使用移动端js实现无缝轮播图效果
<div class="cont">
<div class="swiper">
<div class="swiperlist"><img src="./images/1.jpg" ></div>
<div class="swiperlist"><img src="./images/2.jpg" ></div>
<div class="swiperlist"><img src="./images/3.jpg" ></div>
</div>
</div>
*{
margin: 0;
padding: 0;
}
.cont{
overflow: hidden;
}
.swiper{
display: flex;
margin-left: -100%;
}
.swiperlist{
display: block;
}
.swiperlist img{
display: block;
width: 100%;
}
var swiperlist = document.querySelectorAll('.swiperlist')
var swiper = document.querySelector('.swiper')
swiper.insertBefore(swiperlist[swiperlist.length-1].cloneNode(true),swiperlist[0])
swiper.appendChild(swiperlist[0].cloneNode(true))
var list = swiper.children
swiper.style.width = list.length * 100 + '%'
for(var i = 0 ; i < list.length ; i++){
list[i].style.width = 100/list.length + '%'
}
var cont = document.querySelector('.cont');
var index = 0;
var width_ = cont.clientWidth;
var left = 0;
var X = null;
var x = null;
var loop = true;
cont.ontouchstart = function(e){
if(!loop){ return }
loop = false
setTimeout(function(){
loop = true
},500)
X = e.changedTouches[0].clientX;
swiper.style.transition = null;
cont.ontouchmove = function(e){
x = e.changedTouches[0].clientX;
swiper.style.transform = 'translateX('+ (left-(X-x)) +'px)';
};
cont.ontouchend = function(e){
swiper.style.transition = 'all .5s';
if(X-x > 50){
index++;
if(index >= swiperlist.length){
setTimeout(function(){
swiper.style.transition = 'none';
index = 0
left = -width_ * index;
swiper.style.transform = 'translateX('+ left +'px)';
},500)
}
}else if(X-x < -50){
index--;
if(index<=-1){
swiper.ontransitionend = function(){
swiper.style.transition = 'none';
index = swiperlist.length-1;
left = -width_ * index;
swiper.style.transform = 'translateX('+ left +'px)';
swiper.ontransitionend = null;
}
}
}
left = -width_ * index;
swiper.style.transform = 'translateX('+ left +'px)';
cont.ontouchmove = null
cont.ontouchend = null
}
};