JAVASCRIPT 完美拖拽類

來源:互聯網
上載者:User

拖拽是網頁中經常用到的控制項,因此封裝了一個推拽類。

 

查看示範

<script type="text/javascript">/* new Dragdrop({ * target  拖拽元素 HTMLElemnt 必選 * bridge 指定滑鼠按下哪個元素時開始拖拽,實現模態對話方塊時用到  * dragX  true/false false水平方向不可拖拽 (true)預設 * dragY true/false false垂直方向不可拖拽 (true)預設 * area  [minX,maxX,minY,maxY] 指定拖拽範圍 預設任意拖動 * callback 移動過程中的回呼函數 * });*/function dragDrop(option){this.target=option.target;this.dragX=option.dragX!=false;this.dragY=option.dragY!=false;this.disX=0;this.disY=0;this.bridge =option.bridge;this.area=option.area;this.callback=option.callback;this.target.className="drag";var _this=this; this.bridge?this.brideg.onmousedown=function(e){ _this.mousedown(e)}:this.target.onmousedown=function(e){ _this.mousedown(e)} }dragDrop.prototype={mousedown:function(e){var e=e||event; this.disX=e.clientX-this.target.offsetLeft; this.disY=e.clientY-this.target.offsetTop;this.target.style.cursor = 'move'; if(window.captureEvents){      e.stopPropagation();          e.preventDefault();}  else{e.cancelBubble = true;}var _this=this;var movehandler = function (e) {        _this.move(e)    };var uphandler = function (e) {        _this.mouseup(e)    };document.onmousemove=function(e){_this.move(e)}document.onmouseup=function(e){_this.mouseup(e)}},move:function(e){var e=e||event;var moveX=e.clientX-this.disX;var moveY=e.clientY-this.disY;var _this=this;if(this.area){moveX < _this.area[0] && (moveX = this.area[0]); //left 最小值moveX > _this.area[1] && (moveX = this.area[1]); //left 最大值moveY < _this.area[2] && (moveY = this.area[2]); //top 最小值moveY > _this.area[3] && (moveY = this.area[3]); //top 最大值}this.dragX && (this.target.style.left=moveX+'px');this.dragY && (this.target.style.top=moveY+'px');if(this.callback){var obj = {moveX:moveX,moveY:moveY};this.callback.call(this,obj)}return false}, mouseup:function (e){         var e=e||event;         this.target.style.cursor = 'default';     var _this=this;document.onmousemove=null;document.onmouseup=null;}}</script></head><body><div id="box1"></div>//調用方法:
var box1=document.getElementById('box1');    var d1=new dragDrop({target:box1,area :[0,document.body.clientWidth-100,0,document.body.clientHeight-100],callback:function(obj){box1.innerHTML='x:'+obj.moveX;}})
</body> </html>
相關文章

聯繫我們

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