ts文件
import React, { Component } from 'react'
import './index.less'
export default class index extends Component {
// 触摸位置值
disX: number = 0
// 移动时候的值
x: number = 0
// 父元素的宽
px: number = 0
// 获取线
line = React.createRef<HTMLDivElement>()
// 左球
Lboll?: HTMLDivElement
// 右球
Rboll?: HTMLDivElement
FnStart(e: React.TouchEvent) {
// 获取手指触摸的位置
this.disX = e.changedTouches[0].pageX - (e.target as HTMLDivElement).offsetLeft
// 绑定移动事件
document.ontouchmove = this.FnMove.bind(this)
}
// 移动事件
FnMove(e: TouchEvent) {
// 移动的位置减去我之前盒子的位置,就是我移动后的位置
this.x = e.changedTouches[0].pageX - this.disX
// 保存一份当前线的父元素
const p = (this.line.current as HTMLDivElement).parentElement
// 保存球
const t = e.target as HTMLDivElement
// 如何父元素为nul的话就终止
if (p === null) return false
// 获取父元素的宽
this.px = p.offsetWidth
// 限制球的范围如果移动球的距离小于零,就让他为零,不能为负数 左边球
if (this.x <= 0) this.x = 0
// 父元素的宽减去我球的宽就让this.x重新赋值 限定右球不能出去
if (this.x >= this.px - t.offsetWidth) this.x = this.px - t.offsetWidth
// 获取左球
this.Lboll = p.children[1] as HTMLDivElement
// 获取右球
this.Rboll = p.children[2] as HTMLDivElement
// 判断我右球的偏移量>=我左球的偏移量就执行以下代码
if (this.Rboll.offsetLeft >= this.Lboll.offsetLeft) {
// console.log(this.Lboll.offsetLeft);
// console.log(this.Rboll.offsetLeft);
// 线的left就等于我左球的偏移量
(this.line.current as HTMLDivElement).style.left = this.Lboll.offsetLeft + 'px'
} else {
//如果右球的偏移量小于我左球的偏移量 就让我线的left就等于我右球的偏移量
(this.line.current as HTMLDivElement).style.left = this.Rboll.offsetLeft + 'px'
}
// 线的宽就是右球的偏移量减去我左球的偏移量 它是一个绝对值
(this.line.current as HTMLDivElement).style.width = Math.abs(this.Rboll.offsetLeft - this.Lboll.offsetLeft) + 'px'
// console.log(this.Rboll.offsetLeft - this.Lboll.offsetLeft);
// 如果球的类名为boll也就是true就让他移动
if (t.classList.contains('boll')) t.style.left = this.x + 'px'
console.log(this.x);
}
render() {
return (
<div className='ad'>
<div className="wrap">
<div className="line" ref={this.line}></div>
<div className="boll lc" onTouchStart={this.FnStart.bind(this)}></div>
<div className="boll rc" onTouchStart={this.FnStart.bind(this)}></div>
</div>
</div>
)
}
}
less文件
html,body,#root,.App{
height: 100%;
}
.ad{
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.wrap{
width: 500px;
height: 30px;
background-color: #eee;
position: relative;
}
.line{
width: 100%;
position: absolute;
top: 50%;
transform: translateY(-50%);
height: 30px;
background-color: #ccc;
}
.boll{
width: 50px;
height: 50px;
border-radius: 50%;
background-color: red;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
.rc{
left: 450px;
}