tsx:
import { Component } from "react";
import './drog.sass'
interface Props{}
interface state{
X:number
Y:number
}
class Drog extends Component<Props,state>{
x:number=0
y:number=0
disX:number=0
disY:number=0
constructor(props:Props){
super(props)
this.state = {
X:0,
Y:150
}
}
FnDown(e:any){
this.disX = e.clientX - e.target.offsetLeft
this.disY = e.clientY - e.target.offsetTop
console.log(this.disX,this.disY);
e.target.onmousemove = this.FnMove.bind(this);
e.preventDefault && e.preventDefault()
}
FnMove(e:MouseEvent){
this.x = e.clientX - this.disX
this.y = e.clientY - this.disY
this.setState({
X:this.x,
Y:this.y
})
}
FnUp(e:any):void{
e.target.onmousemove = null;
e.target.onmouseup = null
}
render(){
return (
<div className="drog">
<div className="box" style={{left:this.state.X,top:this.state.Y}} onMouseDown={this.FnDown.bind(this)} onMouseUp={this.FnUp.bind(this)}></div>
</div>
)
}
}
export default Drog
sass:
.drog
.box
height: 200px
width: 200px
position: absolute
background: red
|