本文实例讲述了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程序设计有所帮助。
本文地址:https://www.stayed.cn/item/9058
转载请注明出处。
本站部分内容来源于网络,如侵犯到您的权益,请 联系我