基本逻辑:根据设置定位的top和left完成拖拽
强制刷新还不动:根据本地存储
html部分 js部分
export default class Navbar extends Component {
disX: number = 0
disY: number = 0
x: number = 0
y: number = 0
num: number = 0
drag = createRef<HTMLDivElement>()
DnDown(ev: React.MouseEvent) {
if (this.drag.current) {
this.disX = ev.clientX - this.drag.current.getBoundingClientRect().left
this.disY = ev.clientY - this.drag.current.getBoundingClientRect().top
}
document.onmousemove = this.FnMove.bind(this)
document.onmouseup = this.FnUp.bind(this)
}
FnMove(ev: MouseEvent) {
this.x = ev.clientX - this.disX
this.y = ev.clientY - this.disY
if (this.drag.current) {
this.drag.current.style.top = this.y + "px"
this.drag.current.style.left = this.x + "px"
}
}
FnUp() {
let numx = this.x
let numy = this.y
console.log(numx,"left",numy,"top")
localStorage.setItem("numx", JSON.stringify(numx));
localStorage.setItem("numy", JSON.stringify(numy));
document.onmousemove = null
document.onmouseup = null
}
componentDidMount() {
let SessionX = JSON.parse(localStorage.getItem("numx") as "")
let SessionY = JSON.parse(localStorage.getItem("numy") as "")
if (this.drag.current) {
this.drag.current.style.top = SessionY + "px"
this.drag.current.style.left = SessionX + "px"
}
console.log(SessionX, SessionY)
}
render() {
return (
<nav className="nav-wrapper">
<div className="drag" onMouseDown={this.DnDown.bind(this)} ref={this.drag}></div>
</nav>
)
}
}
css部分
.drag{
position: absolute;
top: 0;
left: 0;
width: 100px;
height: 100px;
background-color: aqua;
}