ts代码部分:
import React, { Component, createRef } from 'react'
import '../css/TestDrag.less'
interface Props {
}
interface State {
}
class TestDrag extends Component<Props, State>{
disX: number = 0;
disY: number = 0;
x: number = 0;
y: number = 0;
dragElement = createRef<HTMLDivElement>();
constructor(props: Props) {
super(props)
this.state = {
}
}
FnDown(ev: React.MouseEvent<HTMLDivElement>): void {
if (this.dragElement.current) {
this.disX = ev.clientX - this.dragElement.current.getBoundingClientRect().left;
this.disY = ev.clientY - this.dragElement.current.getBoundingClientRect().top;
}
document.onmousemove = this.FnMove.bind(this);
document.onmouseup = this.FnUp;
ev.preventDefault && ev.preventDefault()
}
FnMove(ev: MouseEvent) {
this.x = ev.clientX - this.disX;
this.y = ev.clientY - this.disY;
if(this.dragElement.current){
this.dragElement.current.style.left=this.x+'px';
this.dragElement.current.style.top=this.y+'px';
// this.dragElement.current.style.transform = `translate(${this.x}px,${this.y}px)`
}
}
FnUp() {
document.onmousemove=null;
document.onmouseup=null;
}
render() {
return (
<div ref={this.dragElement} className="testdrag" onMouseDown={this.FnDown.bind(this)}></div>
)
}
}
export default TestDrag;
less代码:
没有配置less的也可以用css
.testdrag{
width: 200px;
height: 200px;
background-color: aqua;
position: absolute;
}
版权声明:本文为YanG_2859390447原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。