js实现简单div拖拽功能实例
2015-05-12 14:46
1111 查看
本文实例讲述了js实现简单div拖拽功能的方法。分享给大家供大家参考。具体实现方法如下:
<!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>
希望本文所述对大家的javascript程序设计有所帮助。
您可能感兴趣的文章:
相关文章推荐
- js实现简单div拖拽功能实例
- 利用修改div的位置+js对象存储div信息 实现简单的div自定义布局功能
- js实现简单锁屏功能实例
- js实现简单锁屏功能实例
- jQuery实现div横向拖拽排序的简单实例
- 纯JS实现可拖拽表单的简单实例
- 通过 JS 实现简单的拖拽功能并且可以在特定元素上禁止拖拽
- JS实现的简单拖拽购物车功能示例【附源码下载】
- vuejs2.0运用原生js实现简单的拖拽元素功能
- JS+CSS制作DIV层可(最小化/拖拽/排序)功能实现代码
- Avalonjs 实现简单购物车功能(实例代码)
- vuejs2.0运用原生js实现简单的拖拽元素功能
- vuejs2.0运用原生js实现简单的拖拽元素功能示例
- vuejs2.0运用原生js实现简单的拖拽元素功能
- JS实现的简单拖拽功能示例
- vuejs2.0运用原生js实现简单的拖拽元素功能
- vuejs2.0运用原生js实现简单的拖拽元素功能
- 原生JS实现简单抽人名功能实例
- 用原生JS实现一个简单计算的功能实例
- JS实现的简单表单验证功能完整实例