The example of this article describes the implementation of JS mouse drag-and-drop method. Share to everyone for your reference, specific as follows:
JS Code:
<script> window.onload=function () {var odiv=document.getelementbyid (' div ');
var disx=0;
var disy=0; Odiv.onmousedown=function (EV)//mouse down div {var oevent=ev| |
Event Disx=oevent.clientx-odiv.offsetleft; The mouse's x-coordinate minus the left margin of the div is equal to DISX, this disxs is used to determine the mouse move div when the mouse point and the left distance between the Div, this distance is not change, through the new mouse x coordinates minus DISX is the div's ieft disy= Oevent.clienty-odiv.offsettop;
The y-coordinate of the mouse minus the left margin of the div is equal to Disy, this disy is used to determine the mouse move div when the mouse point and the above distance between the Div, this distance is not change, through the new mouse y-coordinate minus disy is the div top Document.onmousemove=function (EV)//To prevent the mouse movement too fast and left the div created a bug, so to the entire page to add onmousemove event {var oevent=ev| |
Event var Oleft=oevent.clientx-disx; New mouse x coordinates minus DISX, which is left Var otop=oevent.clienty-disy after the mouse moves the div; The new mouse y coordinates minus Disy, that is, the mouse moves the div after the top if (oleft<0)//When the left of the div is less than 0, that is, move out of the left-hand {oleft=0; Left} else if (oleft>document.documentelement.clientwidth-odiv.offsetwidth)//screen width minus the width of the div to get the div to the far right width, if l EFT is larger than this pixel {Oleft=document.documentelement.clientwidtH-odiv.offsetwidth;
The left is set to this pixel} if (otop<0)//When the div's to is less than 0, that is, to move out of {otop=0, or the top of the div is set to 0. else if (otop>document.documentelement.clientheight-odiv.offsetheight)///screen height minus the height of the div results in the div reaching the bottom of the pixel, If top is greater than this pixel {otop=document.documentelement.clientheight-odiv.offsetheight;//The top is set to this pixel} oDi v.style.left=oleft+ ' px '; The left of the DIV is set to the new mouse x coordinates minus the DISX value odiv.style.top=otop+ ' px ';
The top of the div is set to the new mouse y coordinate minus the disy value}; Document.onmouseup=function ()//mouse release {document.onmousemove=null;//Move mouse to clear document.onmouseup=null;//Mice
Mark Loosen Clear}; return false;
Prevent Firefox from default event bugs};
};
</script>
Full code:
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
I hope this article will help you with your JavaScript programming.