tsx:
import React, {Component} from 'react';
import './ball.scss';
class DoubleBall extends Component {
parent: any = React.createRef();
ballOne: any = React.createRef();
ballTwo: any = React.createRef();
lineOne: any = React.createRef();
lineTwo: any = React.createRef();
maxWidth: number = 0;
ballOneStart: number = 0;
ballTwoStart: number = 0;
x: number = 0;
dis: number = 0;
componentDidMount() {
this.maxWidth = this.parent.offsetWidth;
document.ontouchstart = this.touchStart.bind(this);
}
touchStart(e: TouchEvent) {
if ((e.target as HTMLDivElement).className.indexOf('ball') !== -1) {
if ((e.target as HTMLDivElement).className !== 'ball ac') {
this.x = e.targetTouches[0].pageX - this.ballOne.offsetLeft;
} else {
this.x = e.targetTouches[0].pageX - this.ballTwo.offsetLeft;
}
document.ontouchmove = this.touchMove.bind(this);
}
}
touchMove(e: TouchEvent) {
if ((e.target as HTMLDivElement).className.indexOf('ball') !== -1) {
this.dis = e.targetTouches[0].pageX - this.x;
if (this.dis < 0) {
this.dis = 0;
}
if (this.dis > this.maxWidth) {
this.dis = this.maxWidth;
}
if ((e.target as HTMLDivElement).className !== 'ball ac') {
// 左边小球
this.lineOne.style.width = this.dis + 'px';
this.ballOne.style.left = this.dis + 'px';
} else {
// 右边小球
this.ballTwo.style.left = this.dis + 'px';
}
this.lineTwo.style.width = Math.abs(this.ballTwo.offsetLeft - this.ballOne.offsetLeft) + 'px';
this.lineTwo.style.left =
this.ballTwo.offsetLeft - this.ballOne.offsetLeft >= 0 ? this.ballOne.offsetLeft + 'px' : this.ballTwo.offsetLeft + 'px';
}
}
render() {
return (
<div className='double-ball'>
<div className='slide-bar' ref={(div: HTMLDivElement) => (this.parent = div)}>
<div className='line' ref={(div: HTMLDivElement) => (this.lineOne = div)}></div>
<div className='line ac' ref={(div: HTMLDivElement) => (this.lineTwo = div)}></div>
<div className='ball' ref={(div: HTMLDivElement) => (this.ballOne = div)}></div>
<div className='ball ac' ref={(div: HTMLDivElement) => (this.ballTwo = div)}></div>
</div>
</div>
);
}
}
export default DoubleBall;
scss:
.double-ball {
.slide-bar {
width: 700px;
height: 50px;
background: #ccc;
margin: 10px auto;
position: relative;
.line{
position: absolute;
height: 30px;
background: #ccc;
&.ac{
background: lawngreen;
}
}
.ball {
position: absolute;
width: 50px;
height: 50px;
background: goldenrod;
border-radius: 50%;
transform: translateX(-25px);
z-index: 5;
&.ac{
left: 50px;
}
}
}
}