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