Principle: Register the MouseMove event, make the element follow the mouse to move, register the MouseUp event, remove the MouseMove event, so that the element no longer follows the move when releasing the mouse, can be fixed in the specified Position. Registers the MouseMove event and the MouseUp event in the MouseDown event so that a complete drag can be Completed.
Focus: the application of SetCapture () in Ie. Its role is to capture all the mouseevent, after the settings have been completed, even mouse-out Windows registered mouse events can still be triggered. What it does here is that when the mouse moves too fast out of the bounds of the element, the MouseMove event that would otherwise fail will still Work. In the FF and chrome, because there is no corresponding settings, you can assign MouseMove and MouseUp events to the docuemnt object, so no matter how the mouse moves, all on the document, in fact, in ie, so write, then do not set the SetCapture (), the only difference between it and the set is that when the element moves right out of the window boundary, the element is always within the visible range.
JS Code
- <!doctype html>
- <style type="text/css" >
- #drag {border:1px Solid blue;width:100px;height:100px;position:absolute;}
- </style>
- <body>
- <input id="x"/>
- <input id="y"/>
- <div id="drag" ></div>
- <script><!--
- var drag = document.getElementById (' drag ');
- var inputx = document.getElementById (' x ');
- var inputy = document.getElementById (' y ');
- If (document.attachevent) {
- Drag.attachevent (' onmousedown ', draghandle);
- }else{
- Drag.addeventlistener (' MouseDown ', draghandle,false);
- }
- function Draghandle (event) {
- var event = event| | window.event;
- var StartX = drag.offsetleft;
- var starty = drag.offsettop;
- var mousex = event.clientx;
- var mousey = event.clienty;
- var deltax = mousex-startx;
- var deltay = mousey-starty;
- if (document.attachevent) {
- Drag.attachevent (' onmousemove ', movehandle);
- Drag.attachevent (' onmouseup ', uphandle);
- Drag.attachevent (' onlosecapture ', uphandle);
- Drag.setcapture ();
- }else{
- Document.addeventlistener (' MouseMove ', movehandle,true);
- Document.addeventlistener (' MouseUp ', uphandle,true);
- }
- function Movehandle (event) {
- var event = event| | window.event;
- Drag.style.left = (event.clientx-deltax) +"px";
- Drag.style.top = (event.clienty-deltay) +"px";
- inputx.value=drag.style.left;
- inputy.value=drag.style.top;
- }
- function Uphandle () {
- if (document.attachevent) {
- Drag.detachevent (' onmousemove ', movehandle);
- Drag.detachevent (' onmouseup ', uphandle);
- Drag.detachevent (' onlosecapture ', uphandle);
- Drag.releasecapture ();
- }else{
- Document.removeeventlistener (' MouseMove ', movehandle,true);
- Document.removeeventlistener (' MouseUp ', uphandle,true);
- }
- }
- }
- --</script>
- </body>
JS Simple Drag effect