tsx代码
import React,{Component,createRef} from 'react'
import './pull.less'
class Pull extends Component{
Indexone=createRef<HTMLDivElement>()
Parent: any = React.createRef();
BallLeft: any = React.createRef();
BallRight: any = React.createRef();
Line: any = React.createRef();
LineActive: any = React.createRef();
Overall: number = 0;
BallLeftStart: number = 0;
BallRightStart: number = 0;
x: number = 0;
dis: number = 0;
componentDidMount() {
this.Overall = this.Parent.offsetWidth;
document.ontouchstart = this.FnStart.bind(this);
}
FnStart(ev: TouchEvent) {
if ((ev.target as HTMLDivElement).className.indexOf('ball') !== -1) {
if ((ev.target as HTMLDivElement).className !== "ball ac") {
this.x = ev.targetTouches[0].pageX - this.BallLeft.offsetLeft;
} else {
this.x = ev.changedTouches[0].pageX - this.BallRight.offsetLeft;
}
document.ontouchmove = this.FnMove.bind(this)
}
}
FnMove(ev: TouchEvent) {
if ((ev.target as HTMLDivElement).className.indexOf('ball') !== -1) {
this.dis = ev.targetTouches[0].pageX - this.x;
if (this.dis < 0) {
this.dis = 0;
}
if (this.dis > this.Overall) {
this.dis = this.Overall;
}
if ((ev.target as HTMLDivElement).className !== 'ball ac') {
// 左
this.Line.style.width = this.dis + 'px';
this.BallLeft.style.left = this.dis + 'px';
} else {
// 右
this.BallRight.style.left = this.dis + 'px';
}
this.LineActive.style.width = Math.abs(this.BallRight.offsetLeft - this.BallLeft.offsetLeft) + 'px';
this.LineActive.style.left =
this.BallRight.offsetLeft - this.BallLeft.offsetLeft >= 0 ? this.BallLeft.offsetLeft + 'px' : this.BallRight.offsetLeft + 'px';
}
}
FnEnd(ev: TouchEvent) {
}
render(){
return(<div className='double-ball'>
<div className='slide-bar' ref={(div: HTMLDivElement) => (this.Parent = div)}>
<div className='line' ref={(div: HTMLDivElement) => (this.Line = div)}></div>
<div className='line ac' ref={(div: HTMLDivElement) => (this.LineActive = div)}></div>
<div className='ball' ref={(div: HTMLDivElement) => (this.BallLeft = div)}></div>
<div className='ball ac' ref={(div: HTMLDivElement) => (this.BallRight = div)}></div>
</div>
</div>)
}
}
export default Pull
less代码
.double-ball {
.slide-bar {
width: 700px;
height: 20px;
background: skyblue;
margin: 150px auto;
position: relative;
.line{
width: 100%;
position: absolute;
height: 10px;
background: #ccc;
margin-top: 4px;
&.ac{
background: #fff;
}
}
.ball {
position: absolute;
width: 50px;
height: 50px;
background: #f6f6f6;
border: 1px solid #000;
border-radius: 50%;
transform: translateX(-25px);
z-index: 5;
margin-top: -14px;
&.ac{
left: 50px;
}
}
}
}