這篇文章主要介紹了js實現簡單div拖拽功能的方法,實例分析了javascript針對div層拖拽的實現技巧,需要的朋友可以參考下
本文實例講述了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程序設計有所幫助。
新聞熱點
疑難解答
圖片精選