The key to drag is the event source and coordinate position
Basic drag and drop in Web pages:
1. Set whether or not to activate the drag mark flag;
2. When the drag point is pressed, move within the window range;
3. Drag area cannot exceed window, add judgment
Html:
Body>div
CSS code:
<style> div{ width:100px; Height:100px; background: Lightgrey; position: absolute; top:0; Left:0; } </style>
JQ Code:
<script> $(function(){ //whether to activate the dragged logo varFlag =false; varW1 = $ (' div '). width (); varH1 = $ (' div '). Height (); varW2 =$ (window). width (); varH2 =$ (window). Height (); $(' Div '). MouseDown (function() {flag=true; $ (window). MouseMove (function(event) {if(Flag = =true){ varMX =Event.pagex; varmy =Event.pagey; varx = mx-20; vary = my-20; if(x<0) {x=0; } if(y<0) {y=0; } if(x>w2-W1) {x= w2-W1; } if(y>h2-H1) {y=h2-H1; } $(' Div '). css ({left:x,top:y}); } }); }) $ (window). MouseUp (function(event) {/*Act on the event*/Flag=false; }); }) </script>
To specify a drag within the valid range:
1. Drag the three events, drag the mouse button, move within the range of mouse movement, the window within the scope of the mouse release
2. Three distance: 1-The parent box is a distance from the window border; 2. drag point coordinates; 3. The difference between the first two is the approximate position of the drag point in the parent box
3. Note: The drag point must not exceed the box, so you need to add judgment
Html:
Body>div>span
Css:
Div{width:1000px;Height:500px;background:#ccc;Border:1px solid #000;margin:100px Auto;position:relative; }span{width:100px;Height:100px;background:Green;Border:1px solid #000;position:Absolute; Left:0;Top:0; }</style>
JQ:
$(function(){ varDivX = $ (' div '). Offset (). Left; varDivy = $ (' div '). Offset (). Top; varW1 = $ (' span '). width (); varH1 = $ (' span '). Height (); varW2 = $ (' div '). width (); varH2 = $ (' div '). Height (); varFlag =false;//Drag to activate logo$ (' span '). MouseDown (function(event) {flag=true; $(' Div '). MouseMove (function(event) {/*Act on the event*/ varMX =Event.pagex; varmy =Event.pagey; if(Flag = =true){ varx = mx-divx-50;//drag points in the middle of span vary = my-divy-50; //move range in Div if(x <0) {x=0; } if(y<0) {y=0; } if(x>w2-W1) {x=w2-W1; } if(y>h2-H1) {y=h2-H1; } $(' Span '). css ({left:x,top:y}); } }); }); $ (window). MouseUp (function(event) {/*Act on the event*/Flag=false; }); })
Web page Common dynamic effect--drag