js实现拖拽 闭包函数详细介绍_Javascript教程-查字典教程网
js实现拖拽 闭包函数详细介绍
js实现拖拽 闭包函数详细介绍
发布时间:2016-12-30 来源:查字典编辑
摘要:js拖拽采用简单的闭包实现方式复制代码代码如下:/***CreatedwithJetBrainsWebStorm.*User:lsj*Dat...

js拖拽

采用简单的闭包实现方式

复制代码 代码如下:

/**

* Created with JetBrains WebStorm.

* User: lsj

* Date: 12-11-24

* Time: 下午12:59

* To change this template use File | Settings | File Templates.

*/

var dragmanager=(function()

{

//标识移动元素z轴坐标

var index_z=1;

//当前的拖拽元素

var drganow;

//移动标识符号

var dragbegin=false;

//鼠标点击时距离div左边距离

var relativex=0;

//鼠标点击时距离div上边距离

var relativey=0;

//标识鼠标是否移出

var isout=false;

return {

/**

* 为document绑定鼠标提起事件,主要防止鼠标移动过快跳出el区域

*/

bingDocOnMouseUp:function()

{

//注册全局的onmouseup事件,主要防止鼠标移动过快导致鼠标和el不同步

document.onmouseup=function(e)

{

var ev = window.event || e;

if(isout && dragbegin)

{

//改变div的相对位置

drganow.style.left= (ev.clientX-relativex)+'px';

drganow.style.top=(ev.clientY-relativey)+'px';

drganow.style.cursor='normal';

dragbegin=false;

isout=false;

}

}

},

/**

* 将注入的元素绑定事件

* @param el

*/

registerElementEv:function(element)

{

element.onmousedown=function(e)

{

var ev = window.event || e;

var clientx=ev.clientX;

var clienty= ev.clientY;

var left= parseInt(this.style.left.substring(0, this.style.left.indexOf("p")));

var top= parseInt(this.style.top.substring(0, this.style.top.indexOf("p")));

relativex=clientx-left;

relativey=clienty-top;

index_z++;

this.style.zIndex=index_z;

drganow=this;

dragbegin=true;

}

element.onmousemove=function(e)

{

var ev = window.event || e;

//开始拖拽

if(dragbegin)

{

//改变div的相对位置

this.style.left= (ev.clientX-relativex)+'px';

this.style.top=(ev.clientY-relativey)+'px';

this.style.cursor='move';

}

}

element.onmouseout=function(e)

{

isout=true;

}

element.onmouseup=function(e)

{

var ev = window.event || e;

if(dragbegin)

{

//改变div的相对位置

drganow.style.left= (ev.clientX-relativex)+'px';

drganow.style.top=(ev.clientY-relativey)+'px';

drganow.style.cursor='normal';

dragbegin=false;

}

}

}

}

})();

1.采用闭包的形式实现 ,方便后期的维护,将移动过程所需的变量全部转移进gridmanager里面

2.拖拽过程中 鼠标移动过快导致移动元素跟不上鼠标的移动,所以要注册document.oumouseup事件,该事件的开关是有移动元素的onmouseout事件触发的

3.拖拽的过程中可能会触发浏览器自身的onmousemove的select事件,可以进行屏蔽ie下是onmousemove="document.selection.empty()"

相关阅读
推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
  • 大家都在看
  • 小编推荐
  • 猜你喜欢
  • 最新Javascript教程学习
    热门Javascript教程学习
    编程开发子分类