tsx代码
interface Isprops {
}
interface State {
x: number,
y: number
}
export default class index extends Component<Isprops, State> {
x: number = 0
y: number = 0
disX: number = 0
disY: number = 0
boxRef=createRef<HTMLDivElement>()
constructor(props: Isprops) {
super(props);
this.state = {
x: 0,
y: 0
}
}
asBox(){
return this.boxRef.current as HTMLDivElement
}
componentDidMount() {
this.asBox().onmousedown=this.fnStart.bind(this)
if(!localStorage.sData)return
const ww=JSON.parse(localStorage.sData)
if(!ww) return
this.setState({
x:ww.x,
y:ww.y
})
}
fnStart(e:MouseEvent){
this.disX=e.clientX-this.asBox().getBoundingClientRect().left
this.disY=e.clientY-this.asBox().offsetTop
document.onmousemove=this.FnMove.bind(this)
document.onmouseup=this.FnEnd.bind(this)
}
FnMove(e:MouseEvent){
this.x=e.clientX-this.disX;
this.y=e.clientY-this.disY;
this.setState({
x:this.x,
y:this.y
})
}
FnEnd(){
localStorage.sData=JSON.stringify({x:this.x,y:this.y})
document.onmousemove=null
}
render() {
return (
<div className='home'>
<div className='title' ref={this.boxRef} style={{ top: this.state.y + 'px', left: this.state.x + 'px' }}>
</div>
</div>
)
}
}
css代码
body,html{
height:100%;
margin: 0;
}
.title{
width: 200px;
height: 200px;
background-color: aqua;
cursor: pointer;
position:absolute;
}