js實現(xiàn)簡單div拖拽功能實例
更新時間:2015年05月12日 14:46:11 作者:vivi
這篇文章主要介紹了js實現(xiàn)簡單div拖拽功能的方法,實例分析了javascript針對div層拖拽的實現(xiàn)技巧,需要的朋友可以參考下
本文實例講述了js實現(xiàn)簡單div拖拽功能的方法。分享給大家供大家參考。具體實現(xiàn)方法如下:
<!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; //設(shè)置當前對象永遠顯示在最上層 } obj.onmousedown=function (a){ //鼠標按下 this.style.cursor="move"; //設(shè)置鼠標樣式 this.style.zIndex=1000; var d=document; if(!a) a=window.event; //按下時創(chuàng)建一個事件 var x=a.clientX-document.body.scrollLeft-obj.offsetLeft; //x=鼠標相對于網(wǎng)頁的x坐標-網(wǎng)頁被卷去的寬-待移動對象的左外邊距 var y=a.clientY-document.body.scrollTop-obj.offsetTop; //y=鼠標相對于網(wǎng)頁的y左邊-網(wǎng)頁被卷去的高-待移動對象的左上邊距 d.onmousemove=function(a){//鼠標移動 if(!a) a=window.event;//移動時創(chuàng)建一個事件 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";//設(shè)置放開的樣式 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程序設(shè)計有所幫助。
相關(guān)文章
JavaScript 創(chuàng)建隨機數(shù)和隨機圖片
關(guān)于javascript隨機數(shù)的,很早以前的文章了,不過內(nèi)容還是不錯的,如果想要更多的效果,可以去腳本之家搜下。2009-12-12JavaScript前端控制網(wǎng)絡(luò)并發(fā)數(shù)目的常見方法小結(jié)
控制前端發(fā)起請求的并發(fā)數(shù),即限制同一時間內(nèi)進行處理的請求數(shù)量,是一種有效的策略,本文將詳細介紹前端控制并發(fā)數(shù)的幾種常見做法,希望對大家有所幫助2023-12-12