Home > Web Front-end > JS Tutorial > body text

js implementation of simple div drag and drop function example_javascript skills

WBOY
Release: 2016-05-16 15:59:42
Original
1102 people have browsed it

The example in this article describes how to implement simple div drag and drop function in js. Share it with everyone for your reference. The specific implementation method is 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>拖拽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;
 //设置当前对象永远显示在最上层
 }
 obj.onmousedown=function (a){
 //鼠标按下
 this.style.cursor="move";
 //设置鼠标样式
 this.style.zIndex=1000;
  var d=document;
 if(!a) a=window.event;
 //按下时创建一个事件
 var x=a.clientX-document.body.scrollLeft-obj.offsetLeft;
 //x=鼠标相对于网页的x坐标-网页被卷去的宽-待移动对象的左外边距
 var y=a.clientY-document.body.scrollTop-obj.offsetTop;
 //y=鼠标相对于网页的y左边-网页被卷去的高-待移动对象的左上边距
 d.onmousemove=function(a){//鼠标移动
  if(!a) a=window.event;//移动时创建一个事件
  obj.style.left=a.clientX+document.body.scrollLeft-x;
  obj.style.top=a.clientY+document.body.scrollTop-y;
 }
 d.onmouseup=function (){//鼠标放开
  document.onmousemove=null;
  document.onmouseup = null;
  obj.style.cursor="normal";//设置放开的样式
  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>
Copy after login

I hope this article will be helpful to everyone’s JavaScript programming design.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!