using a drag and drop function written by React, there is no problem with the first drag and drop. When you drag the second time, the left,top status of the last image is not saved, and the initialization is the same as the first drag.
/**
* Created by w on 2018/4/4.
*/
import React from "react";
import ReactDOM from "react-dom";
import "./dragAbsolute.css";
class Drag extends React.Component {
constructor(props) {
super(props);
this.state = {
isDragging: false,
mouseX: 0,
mouseY: 0,
left: 0,
top: 0,
lastMovedX: 0,
lastMovedY: 0
};
this.handleMouseDown = this.handleMouseDown.bind(this);
this.handleMouseMove = this.handleMouseMove.bind(this);
this.handleMouseUp = this.handleMouseUp.bind(this);
this.handleMouseLeave = this.handleMouseLeave.bind(this);
}
componentDidMount() {
console.log("mount"); //
this.dragDiv.style.left = "0px";
this.dragDiv.style.top = "0px";
}
handleMouseDown(e) {
let container = this.container;
this.setState({
isDragging: true,
mouseX: e.clientX - container.offsetLeft,
mouseY: e.clientY - container.offsetTop
});
}
handleMouseMove(e) {
let container = this.container;
if (this.state.isDragging) {
let movedX = e.clientX - container.offsetLeft - this.state.mouseX;
let movedY = e.clientY - container.offsetTop - this.state.mouseY;
console.log("moved", movedX, movedY);
console.log("lastMoved", this.state.lastMovedX, this.state.lastMovedY);
let throughX = movedX - this.state.lastMovedX;
let throughY = movedY - this.state.lastMovedY;
console.log("through", throughX, throughY);
this.dragDiv.style.left = parseInt(this.state.left) + throughX + "px";
this.dragDiv.style.top = parseInt(this.state.top) + throughY + "px";
this.setState({
left: this.dragDiv.style.left,
top: this.dragDiv.style.top,
lastMovedX: movedX,
lastMovedY: movedY
});
console.log("state", this.state.left, this.state.top);
}
}
handleMouseUp() {
this.setState({
isDragging: false,
});
}
handleMouseLeave() {
this.setState({
isDragging: false
})
}
render() {
return <div>
<div className="container"
ref={container => {
this.container = container
}}>
<div className="dragImg"
ref={dragDiv => {
this.dragDiv = dragDiv
}}
onMouseDown={this.handleMouseDown}
onMouseMove={this.handleMouseMove}
onMouseUp={this.handleMouseUp}
onMouseLeave={this.handleMouseLeave}
/>
</div>
</div>
}
}
ReactDOM.render(<Drag/>, document.getElementById("root"));
/*CSS*/
*{
margin: 0;
padding: 0;
}
.container{
position: relative;
width: 600px;
height:500px;
border: solid 1px darkturquoise;
overflow: hidden;
margin: 20px auto auto auto;
}
.dragImg{
cursor: move;
position: absolute;
left: 20px;
top:80px;
width: 1805px;
height: 770px;
border: solid 1px lightgrey;
background: url("./img/monitorBg.png");
z-index: 5;
}