Implementation principle and example of jquery simple drag effect

Source: Internet
Author: User

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>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.