Heim  >  Artikel  >  Web-Frontend  >  js实现拖拽 闭包函数详细介绍_javascript技巧

js实现拖拽 闭包函数详细介绍_javascript技巧

WBOY
WBOYOriginal
2016-05-16 17:47:55798Durchsuche
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()"
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn