import React, { Component, createRef } from 'react'
import "./index.less";
export default class index extends Component {
state = { width: "100%", left: 0, lx: -15, rx: 285 }
disx: number = 0
x: number = 0
Element?: HTMLDivElement
parent: number = 0
Fnstart = (ev: React.TouchEvent) => {
this.Element = ev.target as HTMLDivElement
this.disx = ev.changedTouches[0].pageX - this.Element.offsetLeft
}
Fnmove = (ev: React.TouchEvent) => {
var { width, left, lx, rx } = this.state
this.Element = ev.target as HTMLDivElement
this.x = ev.changedTouches[0].pageX - this.disx
if (this.Element.className == "ball") {
lx = this.x
} else {
rx = this.x
}
width = rx - lx + 'px';
this.parent = rx - lx
left = lx + 15
// 小球交互
if (rx < lx) {
width = lx - rx + 'px';
left = rx + 15;
}
// 小球碰撞
// if (this.parent < 30) { // 此处30为小球宽度
// this.Element.className == "ball" ? rx = lx + 30 : lx = rx - 30
// }
this.setState({ width: width, left: left, lx: lx, rx: rx });
}
render() {
var { left, width, lx, rx } = this.state
return (
<div>
<div className='Ball-call'>
<div className="ball" style={{ left: lx + 'px' }} onTouchStart={this.Fnstart} onTouchMove={this.Fnmove}>左</div>
<div className="ballac" style={{ left: rx + 'px' }} onTouchStart={this.Fnstart} onTouchMove={this.Fnmove}>右</div>
<div className="line" style={{ left: left, width: width }}></div>
</div>
</div>
);
}
}
.Ball-call {
width: 300px;
height: 10px;
position: relative;
margin: 100px 0;
font-size: 20px;
margin: 100px auto;
background-color: #999;
.ball,
.ballac {
z-index: 2;
width: 30px;
height: 30px;
border-radius: 50%;
background-color: skyblue;
position: absolute;
text-align: center;
line-height: 30px;
}
.ball {
left: -15px;
top: -10px;
}
.ballac {
right: -15px;
top: -10px;
}
.line {
position: absolute;
left: 0;
width: 100%;
height: 10px;
background-color: red;
}
}
如有高见可在评论区留言
底层逻辑为:判断两侧小球的offsetLeft距离,当左小球比右侧小球的offsetLeft大时,即为正常滑动,但当右侧小球比左侧小球的offsetLeft大时,即证明此时右侧球在左侧,左侧球在右侧,
当左球在左侧时 线的宽度为右侧球的offsetLeft减去左侧球的offsetLeft,线的left值为左球的offsetLeft加上球的宽度
当左侧球在右侧时,线的宽度为左侧球的offsetLeft减去右侧球的offsetLeft,线的left值为右侧球的offsetLeft加上球的宽度
碰撞:
- 底层逻辑为:判断线的宽度,如小于一个球的宽度即为相撞,此时判断如点击的为左测小球即为左侧撞右侧,我们需调整右侧球的left值,他的值为左侧球的offsetLeft加上球的宽度,当点击的为右侧球时,我们需要调整左部球的left值,他的值为右侧球的offsetLeft减上球的宽度