How to use JS to achieve the free movement of multiple images in a Web page

Source: Internet
Author: User

<! 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.