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

2019-12-24,,,

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中的return和闭包函数浅析
  • javascript高级编程之函数表达式 递归和闭包函数
  • javascript 闭包函数做显隐内容
  • 浅谈JavaScript的闭包函数
  • 轻松学习Javascript闭包函数
  • JavaScript 匿名函数(anonymous function)与闭包(closure)
  • js bind 函数 使用闭包保存执行上下文
  • 弱类型语言javascript中 a,b 的运算实例小结

《js实现拖拽 闭包函数详细介绍.doc》

下载本文的Word格式文档,以方便收藏与打印。