<! DOCTYPE html>
<meta charset= "Utf-8" >
<meta http-equiv= "x-ua-compatible" content= "Ie=edge" >
<title>js Drag </title>
<style>
*{padding:0; margin:0;}
. Box{width:100px;height:100px;background:blue;position:absolute;}
</style>
<script src= "Jquery.min.js" ></script>
<script>
var isdown = false;
var objleft, Objtop, PosX, PosY, obj,offsetx,offsety;
$ (function () {
obj=$ ("#box");
Obj.onmousedown = down;
Document.onmousemove = move;
Document.onmouseup = up;
})
Function down (event) {
Isdown=true;
Obj.style.cursor = "Move";
Objleft = Obj.offset (). Left;
Objtop = Obj.offset (). Top;
}
</script>
<script>
var isdown = false;
var objleft, Objtop, PosX, PosY, obj,offsetx,offsety;
Window.onload = function () {
obj = document.getElementById (' box ');
Obj.onmousedown = down;
Document.onmousemove = move;
Document.onmouseup = up;
}
Function down (event) {
Obj.style.cursor = "Move";
Isdown = true;
Objleft = Obj.offsetleft;
Objtop = Obj.offsettop;
PosX = parseint (MousePosition (event). x);
PosY = parseint (MousePosition (event). Y);
Offsetx=posx-objleft;
Offsety=posy-objtop;
}
function Move (event) {
if (Isdown = = True) {
var x=mouseposition (event). X-offsetx;
var y=mouseposition (event). Y-offsety;
var w = document.documentelement.clientwidth-obj.offsetwidth;
var h = document.documentelement.clientheight-obj.offsetheight;
Console.log (x + ', ' + y);
X=math.min (W,math.max (0,x));
Y=math.min (H,math.max (0,y));
Obj.style.left = x + ' px ';
Obj.style.top = y + ' px ';
}
}
function up () {
Isdown = false;
}
function MousePosition (evt) {
var xPos, YPos;
EVT = EVT | | window.event;
if (Evt.pagex) {
XPos = Evt.pagex;
YPos = Evt.pagey;
} else {
XPos = Evt.clientx + document.body.scrollleft-document.body.clientleft;
YPos = Evt.clienty + document.body.scrolltop-document.body.clienttop;
}
return {
X:xpos,
Y:ypos
}
}
</script>
<body>
<div id= "box" class= "box" ></div>
</body>
JavaScript drag and drop