div Drag and drop exercises

Source: Internet
Author: User

After learning JS Foundation, has been looking for some topics in practice. Here is the DIV module drag-and-drop example, not much to say, directly on the code:

<title> Drag </title>
<style type= "Text/css" >
#box {

width:100px;
height:100px;
background:red;
Position:absolute;
}
</style>

<body>
<div id= "box" ></div>
<script type= "Text/javascript" >
Window.onload = drag;

function drag () {
var boxelement = document.getElementById ("box");
Boxelement.onmousedown = function () {
Event = Event | | window.event;
Down (event, box);
}
}

Gets the position of the cursor relative to the div when the mouse is pressed.
function Down (E, EL) {
DISX = Event.clientx-el.offsetleft;
Disy = Event.clienty-el.offsettop;
El.onmousemove = function () {
Event = Event | | window.event;
Move (event, DISX, Disy);
}

Cancel binding of mouse events
El.onmouseup = function () {
El.onmousemove = null;
El.onmouseup = null;
}

}

Div moves according to the position of the cursor
function Move (event, PosX, PosY) {
var boxelement = document.getElementById ("box");
var L = event.clientx-posx;
var t = Event.clienty-posy;
var winw = Document.documentElement.clientWidth | | Document.body.clientWidth;
var Winh = Document.documentElement.clientHeight | | Document.body.clientHeight;
Console.log (winw + "" + Winh);
var maxw = winw-boxelement.offsetwidth;
var maxh = winh-boxelement.offsetheight;
if (L < 0) {
L = 0;
}else if (L > Maxw) {
L = MAXW;
}
if (T < 0) {
t = 0;
}else if (T > Maxh) {
t = maxh;
}

BoxElement.style.left = l + ' px ';
BoxElement.style.top = t + ' px ';
}
</script>
</body>

div Drag and drop exercises

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.