描述:移动端实现无缝轮播
css样式:
body {
margin: 0;
}
.switch-box1 {
width: 100vw;
height: 100vh;
display: flex;
flex-direction: column;
}
.switch-box1 .huan1 {
display: flex;
position: absolute;
overflow: hidden;
height: 81%;
width: 100vw;
}
.switch-box1 .huan1 .huan-box1 {
transition: 0.3s all;
display: flex;
position: absolute;
left: 0vw;
height: 81%;
}
.switch-box1 .huan1 .huan-box1>div:nth-child(2n-1) {
background-color: rgb(216, 56, 56);
}
.switch-box1 .huan1 .huan-box1>div:nth-child(2n) {
background-color: rgb(31, 140, 186);
}
.switch-box1 .huan1 .huan-box1 div {
text-align: center;
font-size: 50px;
line-height: 80px;
width: 100vw;
height: 40%;
}
html代码:
<div class="switch-box1">
<div class="huan1">
<div class="huan-box1">
<div>4</div>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>1</div>
</div>
</div>
</div>
js代码:
let box = document.querySelector('.huan-box1')
let x = 0
let disx = 0
let index = 1
box.style.left = index * -100 + 'vw'
box.ontouchstart = function (e) {
box.style.transition = 'none'
if (index === 0) index = box.children.length - 2
if (index === box.children.length - 1) index = 1
disx = e.changedTouches[0].pageX
document.ontouchmove = function (e) {
x = e.changedTouches[0].pageX - disx
box.style.left = x / 10 + index * -100 + 'vw'
}
document.ontouchend = function () {
document.ontouchmove = null
document.ontouchend = null
if (x < -150) index++
if (x > 150) index--
box.style.transition = '.3s all'
box.style.left = index * -100 + 'vw'
}
return false
}