您好,欢迎访问一九零五行业门户网

工作需要写的一个js拖拽组件_javascript技巧

复制代码 代码如下:
/*
*使用方法:
* 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 样式
完毕!
其它类似信息

推荐信息