DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> JavaScript綜合知識 >> js實現簡單div拖拽功能實例
js實現簡單div拖拽功能實例
編輯:JavaScript綜合知識     

   本文實例講述了js實現簡單div拖拽功能的方法。分享給大家供大家參考。具體實現方法如下:

  ?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 <!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程序設計有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved