知识大全 js实现拖拽 闭包函数详细介绍

Posted 事件

篇首语:宁给好汉拉马,不给懒汉作爷。本文由小常识网(cha138.com)小编为大家整理,主要介绍了知识大全 js实现拖拽 闭包函数详细介绍相关的知识,希望对你有一定的参考价值。

  js拖拽

  采用简单的闭包实现方式

  代码如下:

  /**

  * Created with JetBrains WebStorm

  * User: lsj

  * Date:

  * Time: 下午 :

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

  */

  var dragmanager=(function()

  

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

  var index_z= ;

  //当前的拖拽元素

  var drganow;

  //移动标识符号

  var dragbegin=false;

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

  var relativex= ;

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

  var relativey= ;

  //标识鼠标是否移出

  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( this style left indexOf("p")));

  var top= parseInt(this style top substring( 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;

  

  

  

  

  )();

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

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

cha138/Article/program/Java/JSP/201311/20315

相关参考