这个是移动端的 通过下标来更改父盒子的left值
react部分
import React, { Component,createRef } from 'react'
import './index2.less'
export default class index2 extends Component {
x:number=0
disx:number=0
// 定义下标index 初始值给1
index:number=1
res = createRef<HTMLDivElement>()
list = [4,1,2,3,4,1]
render() {
return (
<div className='switch'>
<div className="switchBox" ref={this.res}>
{this.list.map((item,index)=><div key={index}>{item}</div>)}
</div>
</div>
)
}
box(){
return this.res.current as HTMLDivElement
}
componentDidMount(){
this.box().ontouchstart = this.Fnste.bind(this)
this.box().style.left = this.index*-100+'vw'
}
Fnste(e:TouchEvent){
this.disx = e.changedTouches[0].pageX
this.box().style.transition = 'null'
// 无缝的两个判断
if(this.index == 0) this.index = this.list.length -2
if(this.index == this.list.length -1) this.index = 1
this.box().ontouchmove = this.Fnmove.bind(this)
this.box().ontouchend = this.Fnend.bind(this)
return false
}
Fnmove(e:TouchEvent){
this.x = e.changedTouches[0].pageX - this.disx
this.box().style.left = this.x/10 + this.index*-100+'vw'
}
Fnend(){
this.x == 0?this.box().style.transition = 'null':this.box().style.transition = '.3s all'
if(this.x<-150) this.index++
if(this.x>150) this.index--
this.x = 0
this.box().style.left = this.index*-100+'vw'
}
}
就是在简单的轮播基础上加上判断
判断下标等于0的时候更改成list里面的倒数第二个 当下标等于最后一个的时候更改成下标1
less部分
.switch {
position: absolute;
overflow: hidden;
height: 81%;
width: 100vw;
.switchBox {
transition: 0.3s all;
display: flex;
position: absolute;
left: 0vw;
height: 81%;
>div:nth-child(2n-1) {
background-color: rgb(216, 56, 56);
}
>div:nth-child(2n) {
background-color: rgb(31, 140, 186);
}
div {
text-align: center;
font-size: 50px;
line-height: 80px;
width: 100vw;
height: 40%;
}
}
}