preface
The latest need to implement a drag and drop to change the height of the component function, I always thought it was very simple, today I found that there are still some things to pay attention to, especially in this record.
The principle of
In fact, the principle is not complicated, the general code is as follows:
let startX = startY = 0, draging = false;
const handleMouseDown = event= > {
draging = true;
startX = event.screenX;
startY = event.screenY;
}
const handleMouseMove = event= > {
if(draging) {
// Here is the drop down border and the right border
// The opposite is true for left and top borderselement.width += (event.startX - startX); element.height += (event.startY - startY); startX = event.startX; startY = event.startY; }}const handleMouseUp = () = > {
draging = false;
startX = startY = 0;
}
Copy the code
Points to be aware of
It’s not that complicated, but if mousedown, Mousemove, and Mouseup all listen to the border, it’s easy to move the mouse out of the border, and the terminal can’t start mouseup. In this case, we need to listen for the Document mousemove and mouseup, and then remove the listener from the mouseup event.
const handleMouseDown = event= > {
draging = true;
startX = event.screenX;
startY = event.screenY;
document.addEventListener('mousemove', handleMouseMove, true);
document.addEventListener('mouseup', handleMouseUp, true);
}
const handleMouseMove = event= > {
if(draging) {
// Here is the drop down border and the right border
// The opposite is true for left and top borderselement.width += (event.startX - startX); element.height += (event.startY - startY); startX = event.startX; startY = event.startY; }}const handleMouseUp = () = > {
document.removeEventListener('mousemove', handleMouseMove, true);
document.removeEventListener('mouseup', handleMouseUp, true);
draging = false;
startX = startY = 0;
}
Copy the code
Specific demo then fill up, sleep sleep ~