復制代碼 代碼如下:
/*
*使用方法:
* var d = new Drag({id:'dragPannel',maxLeft:500,maxTop:200});
* d.ready();
*請注意:
* 拖動對象的left和top樣式必須寫在其style屬性裡邊
*
*/
//矯正調用者。將 fn 作為 newObj 的方法調用
function repairCaller(newObj, fn){
return function(){
return fn.apply(newObj, arguments);
}
}
function Drag( config ){
this.moveTarget = T.dom.get( config.id );
this.startLeft = parseInt(this.moveTarget.style.left); //每次拖動開始時被拖動對象的 left,top
this.startTop = parseInt(this.moveTarget.style.top);
this.startClientX = this.startLeft; //保存拖動開始時事件的 clientX, clientY
this.startClientY = this.startTop;
this.MAX_LEFT = config.maxLeft||document.documentElement.clientWidth - this.moveTarget.offsetWidth; //元素可以移動的最大范圍
this.MAX_TOP = config.maxTop||document.documentElement.clientHeight - this.moveTarget.offsetHeight;
this.lock = true;
}
Drag.prototype.ready = function(){
//綁定事件
T.bind(document, "mousedown", repairCaller(this,this.down));
T.bind(document, "mousemove", repairCaller(this,this.move));
T.bind(document, "mouseup", repairCaller(this,this.stop));
}
Drag.prototype.down = function(){
//取得事件對象
var event = T.event.getEvent(arguments[0]),
target = T.event.getTarget(event);
if (target == this.moveTarget){
this.lock = false;
//在事件開始時保存各種坐標位置
this.startLeft = parseInt(this.moveTarget.style.left);
this.startTop = parseInt(this.moveTarget.style.top);
this.startClientX = event.clientX;
this.startClientY = event.clientY;
}
};
Drag.prototype.move = function(){
if(!this.lock ){
//取得事件對象
var event = T.event.getEvent(arguments[0]),
target = T.event.getTarget(event);
if(target == this.moveTarget){
//如有選擇內容,清除之
//window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
//湊數拖動范圍有沒超過最大限制
var realLeft = this.startLeft + event.clientX - this.startClientX, //實際的移動范圍
realTop = this.startTop + event.clientY - this.startClientY,
rightLeft , rightTop; //正確的 left, top 取值
rightLeft = realLeft > this.MAX_LEFT ? this.MAX_LEFT : ( realLeft > 0 ? realLeft : 0 );
rightTop = realTop > this.MAX_TOP ? this.MAX_TOP : ( realTop > 0 ? realTop : 0 );
this.moveTarget.style.left = rightLeft + "px";
this.moveTarget.style.top = rightTop + "px";
}
else{
this.lock = true;
}
}
};
Drag.prototype.stop = function(){
this.lock = true
};
後記:
在寫的過程中非常需要注意的幾點是:
1、拖動層的 position、left 和 top 必須寫在 style 裡
2、移動過程中設置 left 和 top 要帶單位,否則不起作用
3、多級 div 嵌套時需要給父 div 加 over-flow:hidden 樣式
完畢!