js implements a simple div drag and drop function instance
- 2020-06-12 08:27:34
- OfStack
This article illustrates how js implements simple div drag-and-drop functionality. Share to everybody for everybody reference. Specific implementation methods are as follows:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> Drag and drop div</title>
<style type="text/css">
div{
position:absolute;
width:150px;
height:150px;
background-color:#C8FFFF;
}
</style>
<script type="text/javascript">
<!--
function drag(obj)
{
if (typeof obj == "string") {
var obj = document.getElementById(obj);
obj.orig_index=obj.style.zIndex;
// Sets the current object to always appear at the top level
}
obj.onmousedown=function (a){
// The mouse click
this.style.cursor="move";
// Set the mouse style
this.style.zIndex=1000;
var d=document;
if(!a) a=window.event;
// Create when pressed 1 An event
var x=a.clientX-document.body.scrollLeft-obj.offsetLeft;
//x= Mouse relative to the web page x coordinates - The width of a web page being rolled out - The left margin of the object to be moved
var y=a.clientY-document.body.scrollTop-obj.offsetTop;
//y= Mouse relative to the web page y On the left - The page is rolled high - The left top margin of the object to be moved
d.onmousemove=function(a){// The mouse moves
if(!a) a=window.event;// Create while moving 1 An event
obj.style.left=a.clientX+document.body.scrollLeft-x;
obj.style.top=a.clientY+document.body.scrollTop-y;
}
d.onmouseup=function (){// The mouse go
document.onmousemove=null;
document.onmouseup = null;
obj.style.cursor="normal";// Set the open style
obj.style.zIndex=obj.orig_index;
}
}
}
-->
</script>
</head>
<body>
<div id="div1"> </div>
<div id="div2" style="left:170px; background-color:#408080"></div>
<script type="text/javascript">
<!--
drag("div1");
drag("div2");
-->
</script>
</body>
</html>
Hopefully, this article has been helpful in your javascript programming.