js:簡單的拖動效果,js拖動效果

來源:互聯網
上載者:User

js:簡單的拖動效果,js拖動效果

效果示範:https://jsfiddle.net/dwqs/b5ywws9f/embedded/result/

html:

<div class="wrap">    <div id="boxmove" style="left:150px;top:150px;"> movebox </div> </div>

css

#boxmove{        position: absolute;        width: 200px;        border:1px solid #ccc;        height: 200px;        color: red;        background-color: blue;        text-align: center;        font-size: 30px;    }

js

var o,   //捕獲到的事件      X,  //boxmove水平寬度      Y;  //boxmove垂直高度function getObject(obj,e){    //擷取捕獲到的對象    o = obj;    // document.all(IE)使用setCapture方法綁定;其餘比如FF使用
//Window對象針對事件的捕捉    document.all?o.setCapture() : window.captureEvents(Event.MOUSEMOVE);      X = e.clientX - parseInt(o.style.left);   //擷取寬度,    Y = e.clientY - parseInt(o.style.top);   //擷取高度,}document.getElementById("boxmove").onmousedown = function(e){     
//boxmove捕獲事件並處理  e-->FF  window.event-->IE
getObject(this,e||event);       };document.onmousemove = function(dis){    //滑鼠移動事件處理    if(!o){          return;    }    if(!dis){  //事件        dis = event ;    }
//設定boxmovebox樣式隨滑鼠移動而改變
o.style.left = dis.clientX - X +"px";  
o.style.top = dis.clientY - Y + "px";};
document.onmouseup = function(){    
//滑鼠鬆開事件處理    
if(!o){ return; }    

// document.all(IE)使用releaseCapture解除綁定;
//其餘比如FF使用window對象針對事件的捕捉
    document.all?o.releaseCapture() : window.captureEvents(
Event.MOUSEMOVE|Event.MOUSEUP)    o = '';   //還Null 物件};

需要注意的是,因為需要更改div的left和top。這兩個屬性需要以內聯方式給出,否則不行。

原文:http://www.ido321.com/1489.html

參考文檔:

https://developer.mozilla.org/en-US/docs/Web/API/Window/captureEvents

https://developer.mozilla.org/zh-CN/docs/Web/API/element/setCapture

https://developer.mozilla.org/zh-CN/docs/Web/API/Document/releaseCapture

聯繫我們

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