拖拽是網頁中經常用到的控制項,因此封裝了一個推拽類。
查看示範
<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>