Copy codeThe Code is as follows:
<! DOCTYPE html>
<Html>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
<Title> simple drag-and-drop principle instance </title>
<Style type = "text/css">
# Drag {width: 400px; height: 300px; background: url (http://upload.yxgz.cn/uploadfile/2009/0513/20090513052611873.jpg); cursor: move; position: absolute; top: 100px; left: 100px; border: solid 1px # ccc ;}
H2 {color: # fff; background: none repeat scroll 0 0 rgba (16, 90, 31, 0.7); color: # FFFFFF; height: 40px; line-height: 40px; margin: 0 ;}
</Style>
<Script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type = "text/javascript"> </script>
<Script type = "text/javascript">
$ (Function (){
/* -------------- Drag effect ----------------
* Principle: dragging, coordinate position iX, iY
* Mousedown: fn () {dragging = true, record start Coordinate Position, set Mouse capture}
* Mouseover: fn () {determine if dragging is set to true, then the current coordinate position-the starting Coordinate Position of the record, and the difference value is obtained for the absolutely positioned element}
* Mouseup: fn () {dragging = false, release Mouse capture to prevent bubbling}
*/
Var dragging = false;
Var iX, iY;
$ ("# Drag"). mousedown (function (e ){
Dragging = true;
IX = e. clientX-this. offsetLeft;
IY = e. clientY-this. offsetTop;
This. setCapture & this. setCapture ();
Return false;
});
Document. onmousemove = function (e ){
If (dragging ){
Var e = e | window. event;
Var oX = e. clientX-iX;
Var oY = e. clientY-iY;
$ ("# Drag" ).css ({"left": oX + "px", "top": oY + "px "});
Return false;
}
};
$ (Document). mouseup (function (e ){
Dragging = false;
$ ("# Drag") [0]. releaseCapture ();
E. cancelBubble = true;
})
})
</Script>
</Head>
<Body>
<Div id = "drag">
<H2> drag me here </Div>
</Body>
</Html>