js實現簡單div拖拽功能執行個體,jsdiv拖拽執行個體

來源:互聯網
上載者:User

js實現簡單div拖拽功能執行個體,jsdiv拖拽執行個體

本文執行個體講述了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程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.