JQuery drag and drop div implementation idea

  • 2020-03-30 01:46:51
  • OfStack

The idea is to use jquery's mousemove, mousedown and mouseup events to define two relative positions, respectively

1. The relative position of the upper left corner of the component and the upper left corner of the screen

2. The coordinate of the mouse is relative to the upper left corner of the component.

The specific function is as follows:

 
.drag{ 
position:absolute; 
background:#0000CC; 
top:100px;left:200px; 
padding:0; 
} 

 
$(document).ready(function(){ 
var move=false;//Mobile tag
var _x,_y;//The position of the mouse relative to the upper left corner of the control
$(".drag").mousedown(function(e){ 
move=true; 
_x=e.pageX-parseInt($(".drag").css("left")); 
_y=e.pageY-parseInt($(".drag").css("top")); 
}); 
$(document).mousemove(function(e){ 
if(move){ 
var x=e.pageX-_x;//The relative position of the upper left corner of the control to the upper left corner of the screen
var y=e.pageY-_y; 
$(".drag").css({"top":y,"left":x}); 
} 
}).mouseup(function(){ 
move=false; 
}); 

Where, e.pagagex and e.pagey are the horizontal and vertical coordinates of the current mouse.

We try their own hands, the train of thought is more clear ~

Related articles: