javascript拖住布局demo

來源:互聯網
上載者:User

<script type="text/javascript">

   /*分析:整個過程分三步走,分別是:擷取對象,移動對象,釋放對象

     這三個步驟用滑鼠的事件來對應是:onmousedown,onmousemove,onmouseup

   */
    var x,y,z,down=false,obj;
    function init(){
        obj=event.srcElement;       //擷取焦點對象
        obj.setCapture();              //設定滑鼠捕捉
        z=obj.style.zIndex;           //取得原z軸位置
        obj.style.zIndex=100;       //設定在最上層
        x=event.offsetX;              //擷取滑鼠指標相對於觸發事件的對象的x位置
        y=event.offsetY;              //擷取滑鼠指標相對於觸發事件的對象的y位置
        down=true;                     //設定滑鼠狀態為按下狀態
    }
    function move(){
        if(down&&event.srcElement==obj){
            with(obj.style){
                posLeft=document.body.scrollLeft+event.x-x;
                posTop=document.body.scrollTop+event.y-y;
            }
        }
    }
    function up(){
        down=false;
        obj.style.zIndex=z;
        obj.releaseCapture();
    }
  </script>
</head>
 
<div id="1" onmousedown="init()" onmousemove="move()" onmouseup="up()" style="position:absolute;top:100px;left:100px;
width:100px;height:150px;border:1px solid #ccc;background:red;z-index:1">div1</div>
<div id="2" onmousedown="init()" onmousemove="move()" onmouseup="up()" style="position: absolute;top:150px;left:150px;
width:100px;height:150px;border:1px solid #666;background:blue;z-index:2">div2</div>
<div id="3" onmousedown="init()" onmousemove="move()" onmouseup="up()" style="position: absolute;top:200px;left:200px;
width:100px;height:150px;border:1px solid #999;background:green;z-index:3;">div3</div>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.