less:
.ad{
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.wrap{
width: 500px;
height: 10px;
background-color: #000;
position: relative;
}
.line{
width: 100%;
position: absolute;
top: 50%;
transform: translateY(-50%);
height: 10px;
background-color: #ccc;
}
.boll{
width: 50px;
height: 50px;
border-radius: 50%;
background-color: palevioletred;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
.rc{
left: 450px;
}
ts:
import React, { Component, createRef } from "react";
import './index.less'
export default class collidec extends Component {
// 获取线元素
line: React.RefObject<HTMLDivElement> = createRef<HTMLDivElement>()
// 存值
disx: number = 0
// 移动的值
x: number = 0
// 获取左边的小球
Lboll?: HTMLDivElement
// 获取右边的小球
Rboll?: HTMLDivElement
// 获取父元素
parentElement: React.RefObject<HTMLDivElement> = React.createRef<HTMLDivElement>()
// 父元素的宽度
px: number = 0
// 判断目标元素
target?: HTMLDivElement
// 封装线元素
GetLine() {
return this.line.current as HTMLDivElement
}
// 封装父元素
Parent() {
return this.parentElement.current as HTMLDivElement
}
// 绑定移动事件
Fnstart(ev: React.TouchEvent) {
this.disx = ev.changedTouches[0].pageX - (ev.target as HTMLDivElement).offsetLeft
document.ontouchmove = this.Fnmove.bind(this)
}
Fnmove(ev: TouchEvent) {
this.x = ev.changedTouches[0].pageX - this.disx
// console.log(this.line.current as HTMLDivElement);
this.target = ev.target as HTMLDivElement
// 限制两边球滑动的宽度 (获取父元素的宽度)
this.px = this.Parent().offsetWidth
// console.log(this.px);
// 获取左边的小球 父元素的第一个孩子
this.Lboll = this.Parent().children[1] as HTMLDivElement
// 获取右边的小球 父元素的第二个孩子
this.Rboll = this.Parent().children[2] as HTMLDivElement
if (this.x < 0) this.x = 0
// 移动的值大于父元素的宽度-两个小球的宽度
if (this.x >= this.px - this.target.offsetWidth) this.x = this.px - this.target.offsetWidth
// 如果右边的球大于左边的小球
if (this.Rboll.offsetLeft >= this.Lboll.offsetLeft) {
this.GetLine().style.left = this.Lboll.offsetLeft + 'px'
// 否则右边的小球小于左边的小球
} else {
this.GetLine().style.left = this.Rboll.offsetLeft + 'px'
}
this.GetLine().style.width = Math.abs(this.Rboll.offsetLeft - this.Lboll.offsetLeft) + 'px'
if (this.target.classList.contains('boll')) this.target.style.left = this.x + 'px'
}
render() {
return (
<div className="ad">
<div className="wrap" ref={this.parentElement}>
<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>
)
}
}
小球交叉展示