A small example of using JS to implement drag and drop

Source: Internet
Author: User

Code:

1 <!DOCTYPE HTML>2 <HTMLLang= "en">3 <Head>4     <MetaCharSet= "UTF-8">5     <title>Title</title>6 7     <style>8 9 Body{Ten margin:0; One         } A  - #rect{ - width:100px; the Height:100px; - Background-color:Red; - position:fixed; -         } +  -     </style> +  A </Head> at <Body> -  - <DivID= "Rect"></Div> -  - <Scriptsrc= "Main.js"></Script> - </Body> in </HTML>
HTML
1 /**2 * Created by Plter on 8/12/16.3  */4 5(function () {6 7     varRect = Document.queryselector ("#rect");8 9     varRectx = 0, recty = 0, OffsetX, OffsetY;Ten  OneRect.onmousedown =function(event) { AOffsetX = Rectx-Event.pagex; -OffsetY = Recty-Event.pagey; -  theDocument.onmousemove =function(event) { -Rectx = Event.pagex +OffsetX; -Recty = Event.pagey +OffsetY; -  +Rect.style.left = rectx + "px"; -Rect.style.top = recty + "px"; +         }; A  atDocument.onmouseup =function(event) { -Document.onmousemove =NULL; -Document.onmouseup =NULL; -         } -     } -  in})();
JS

Note two points:

①: When you start dragging, you should judge the position of the drag point.

②: You can "put it down" when you are not dragging.

This is also very useful, such as the famous aircraft war.

A small example of using JS to implement drag and drop

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.