<! DOCTYPE html>
<meta charset= "Utf-8"/>
<title></title>
<style type= "Text/css" >
div{
Position:absolute;
width:200px;
height:200px;
Background-color: #ccc;
}
</style>
<body style= "position:relative;" >
<div style= "top:50px;left:100px;" >
I can be dragged.
</div>
<div style= "top:100px;left:300px;" >
I can be dragged.
</div>
<script type= "Text/javascript" >
var div = document.getelementsbytagname (' div ') [0];
var mousex = 0,mousey=0;
var divy = 0;//parseint (div.style.top);//current element distance from top left corner of window
var DivX = 0;//parseint (div.style.left);
Console.info (Div.style.top,div.style.left);
Div.onmousedown =function (e) {
mouse button down:
1. Get the position of the current element
2. Get the position of the mouse
Divy = parseint (div.style.top);//current element distance from top left corner of window
DivX = parseint (div.style.left);
E = e | | Event
MouseX = E.clientx;
Mousey = E.clienty;
Console.info (Mousex,mousey);
Record the current mouse position
Div.onmousemove = function (e) {
Document.onmousemove = function (e) {
E = e | | Event
Get the new location of the mouse
var currentx = E.clientx;
var currenty = E.clienty;
New position of the calculated element
var divnewx = divx-mousex + CurrentX;
var divnewy = Divy-mousey + currenty;
Div.style.top = divnewy + "px";
Div.style.left = divnewx + "px";
Console.info ("OnMouseMove", divnewx,divnewy);
}
}
Div.onmouseup =function (e) {
Div.onmousemove = null;
Document.onmousemove = null;
Console.info ("onmouseup")
}
</script>
</body>
How to use JS to achieve the free movement of multiple images in a Web page