拖动Html元素集合 Drag and Drop any item


Posted in Javascript onDecember 22, 2006

<style content="text/css">
li {
  MARGIN-BOTTOM: 10px
}
ul {
  MARGIN-TOP: 5px
}
.DragContainer {
  BORDER-RIGHT: #669999 2px solid; PADDING-RIGHT: 5px; BORDER-TOP: #669999 2px solid; PADDING-LEFT: 5px; FLOAT: left; PADDING-BOTTOM: 0px; MARGIN: 3px; BORDER-LEFT: #669999 2px solid; WIDTH: 100px; PADDING-TOP: 5px; BORDER-BOTTOM: #669999 2px solid
}
.OverDragContainer {
  BORDER-RIGHT: #669999 2px solid; PADDING-RIGHT: 5px; BORDER-TOP: #669999 2px solid; PADDING-LEFT: 5px; FLOAT: left; PADDING-BOTTOM: 0px; MARGIN: 3px; BORDER-LEFT: #669999 2px solid; WIDTH: 100px; PADDING-TOP: 5px; BORDER-BOTTOM: #669999 2px solid
}
.OverDragContainer {
  BACKGROUND-COLOR: #eee
}
.DragBox {
  BORDER-RIGHT: #000 1px solid; PADDING-RIGHT: 2px; BORDER-TOP: #000 1px solid; PADDING-LEFT: 2px; FONT-SIZE: 10px; MARGIN-BOTTOM: 5px; PADDING-BOTTOM: 2px; BORDER-LEFT: #000 1px solid; WIDTH: 94px; CURSOR: pointer; PADDING-TOP: 2px; BORDER-BOTTOM: #000 1px solid; FONT-FAMILY: verdana, tahoma, arial; BACKGROUND-COLOR: #eee
}
.OverDragBox {
  BORDER-RIGHT: #000 1px solid; PADDING-RIGHT: 2px; BORDER-TOP: #000 1px solid; PADDING-LEFT: 2px; FONT-SIZE: 10px; MARGIN-BOTTOM: 5px; PADDING-BOTTOM: 2px; BORDER-LEFT: #000 1px solid; WIDTH: 94px; CURSOR: pointer; PADDING-TOP: 2px; BORDER-BOTTOM: #000 1px solid; FONT-FAMILY: verdana, tahoma, arial; BACKGROUND-COLOR: #eee
}
.DragDragBox {
  BORDER-RIGHT: #000 1px solid; PADDING-RIGHT: 2px; BORDER-TOP: #000 1px solid; PADDING-LEFT: 2px; FONT-SIZE: 10px; MARGIN-BOTTOM: 5px; PADDING-BOTTOM: 2px; BORDER-LEFT: #000 1px solid; WIDTH: 94px; CURSOR: pointer; PADDING-TOP: 2px; BORDER-BOTTOM: #000 1px solid; FONT-FAMILY: verdana, tahoma, arial; BACKGROUND-COLOR: #eee
}
.miniDragBox {
  BORDER-RIGHT: #000 1px solid; PADDING-RIGHT: 2px; BORDER-TOP: #000 1px solid; PADDING-LEFT: 2px; FONT-SIZE: 10px; MARGIN-BOTTOM: 5px; PADDING-BOTTOM: 2px; BORDER-LEFT: #000 1px solid; WIDTH: 94px; CURSOR: pointer; PADDING-TOP: 2px; BORDER-BOTTOM: #000 1px solid; FONT-FAMILY: verdana, tahoma, arial; BACKGROUND-COLOR: #eee
}
.OverDragBox {
  BACKGROUND-COLOR: #ffff99
}
.DragDragBox {
  BACKGROUND-COLOR: #ffff99
}
.DragDragBox {
  FILTER: alpha(opacity=50); BACKGROUND-COLOR: #ff99cc
}
LEGEND {
  FONT-WEIGHT: bold; FONT-SIZE: 12px; COLOR: #666699; FONT-FAMILY: verdana, tahoma, arial
}
FIELDSET {
  PADDING-RIGHT: 3px; PADDING-LEFT: 3px; PADDING-BOTTOM: 3px; PADDING-TOP: 3px
}
.History {
  FONT-SIZE: 10px; OVERFLOW: auto; WIDTH: 100%; FONT-FAMILY: verdana, tahoma, arial; HEIGHT: 82px
}
#DragContainer8 {
  BORDER-RIGHT: #669999 1px solid; PADDING-RIGHT: 0px; BORDER-TOP: #669999 1px solid; PADDING-LEFT: 5px; PADDING-BOTTOM: 0px; BORDER-LEFT: #669999 1px solid; WIDTH: 110px; PADDING-TOP: 5px; BORDER-BOTTOM: #669999 1px solid; HEIGHT: 110px
}
.miniDragBox {
  FLOAT: left; MARGIN: 0px 5px 5px 0px; WIDTH: 20px; HEIGHT: 20px
}
pre{border:1 solid #CCC;background-color:#F8F8F0;padding:10px;}
</style>
<script content="text/javascript">

// iMouseDown represents the current mouse button state: up or down
/*
lMouseState represents the previous mouse button state so that we can
check for button clicks and button releases:

if(iMouseDown && !lMouseState) // button just clicked!
if(!iMouseDown && lMouseState) // button just released!
*/
var mouseOffset = null;
var iMouseDown = false;
var lMouseState = false;
var dragObject = null;

// Demo 0 variables
var DragDrops = [];
var curTarget = null;
var lastTarget = null;
var dragHelper = null;
var tempDiv = null;
var rootParent = null;
var rootSibling = null;

Number.prototype.NaN0=function(){return isNaN(this)?0:this;}

function CreateDragContainer(){
  /*
  Create a new "Container Instance" so that items from one "Set" can not
  be dragged into items from another "Set"
  */
  var cDrag = DragDrops.length;
  DragDrops[cDrag] = [];

  /*
  Each item passed to this function should be a "container". Store each
  of these items in our current container
  */
  for(var i=0; i<arguments.length; i++){
    var cObj = arguments[i];
    DragDrops[cDrag].push(cObj);
    cObj.setAttribute('DropObj', cDrag);

    /*
    Every top level item in these containers should be draggable. Do this
    by setting the DragObj attribute on each item and then later checking
    this attribute in the mouseMove function
    */
    for(var j=0; j<cObj.childNodes.length; j++){

      // Firefox puts in lots of #text nodes...skip these
      if(cObj.childNodes[j].nodeName=='#text') continue;

      cObj.childNodes[j].setAttribute('DragObj', cDrag);
    }
  }
}

function mouseCoords(ev){
  if(ev.pageX || ev.pageY){
    return {x:ev.pageX, y:ev.pageY};
  }
  return {
    x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
    y:ev.clientY + document.body.scrollTop - document.body.clientTop
  };
}

function getMouseOffset(target, ev){
  ev = ev || window.event;

  var docPos = getPosition(target);
  var mousePos = mouseCoords(ev);
  return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
}

function getPosition(e){
  var left = 0;
  var top = 0;
  while (e.offsetParent){
    left += e.offsetLeft + (e.currentStyle?(parseInt(e.currentStyle.borderLeftWidth)).NaN0():0);
    top += e.offsetTop + (e.currentStyle?(parseInt(e.currentStyle.borderTopWidth)).NaN0():0);
    e = e.offsetParent;
  }

  left += e.offsetLeft + (e.currentStyle?(parseInt(e.currentStyle.borderLeftWidth)).NaN0():0);
  top += e.offsetTop + (e.currentStyle?(parseInt(e.currentStyle.borderTopWidth)).NaN0():0);

  return {x:left, y:top};

}

function mouseMove(ev){
  ev = ev || window.event;

  /*
  We are setting target to whatever item the mouse is currently on

  Firefox uses event.target here, MSIE uses event.srcElement
  */
  var target = ev.target || ev.srcElement;
  var mousePos = mouseCoords(ev);

  // mouseOut event - fires if the item the mouse is on has changed
  if(lastTarget && (target!==lastTarget)){
    // reset the classname for the target element
    var origClass = lastTarget.getAttribute('origClass');
    if(origClass) lastTarget.className = origClass;
  }

  /*
  dragObj is the grouping our item is in (set from the createDragContainer function).
  if the item is not in a grouping we ignore it since it can't be dragged with this
  script.
  */
  var dragObj = target.getAttribute('DragObj');

   // if the mouse was moved over an element that is draggable
  if(dragObj!=null){

    // mouseOver event - Change the item's class if necessary
    if(target!=lastTarget){
      var oClass = target.getAttribute('overClass');
      if(oClass){
        target.setAttribute('origClass', target.className);
        target.className = oClass;
      }
    }

    // if the user is just starting to drag the element
    if(iMouseDown && !lMouseState){
      // mouseDown target
      curTarget = target;

      // Record the mouse x and y offset for the element
      rootParent = curTarget.parentNode;
      rootSibling = curTarget.nextSibling;

      mouseOffset = getMouseOffset(target, ev);

      // We remove anything that is in our dragHelper DIV so we can put a new item in it.
      for(var i=0; i<dragHelper.childNodes.length; i++) dragHelper.removeChild(dragHelper.childNodes[i]);

      // Make a copy of the current item and put it in our drag helper.
      dragHelper.appendChild(curTarget.cloneNode(true));
      dragHelper.style.display = 'block';

      // set the class on our helper DIV if necessary
      var dragClass = curTarget.getAttribute('dragClass');
      if(dragClass){
        dragHelper.firstChild.className = dragClass;
      }

      // disable dragging from our helper DIV (it's already being dragged)
      dragHelper.firstChild.removeAttribute('DragObj');

      /*
      Record the current position of all drag/drop targets related
      to the element. We do this here so that we do not have to do
      it on the general mouse move event which fires when the mouse
      moves even 1 pixel. If we don't do this here the script
      would run much slower.
      */
      var dragConts = DragDrops[dragObj];

      /*
      first record the width/height of our drag item. Then hide it since
      it is going to (potentially) be moved out of its parent.
      */
      curTarget.setAttribute('startWidth', parseInt(curTarget.offsetWidth));
      curTarget.setAttribute('startHeight', parseInt(curTarget.offsetHeight));
      curTarget.style.display = 'none';

      // loop through each possible drop container
      for(var i=0; i<dragConts.length; i++){
        with(dragConts[i]){
          var pos = getPosition(dragConts[i]);

          /*
          save the width, height and position of each container.

          Even though we are saving the width and height of each
          container back to the container this is much faster because
          we are saving the number and do not have to run through
          any calculations again. Also, offsetHeight and offsetWidth
          are both fairly slow. You would never normally notice any
          performance hit from these two functions but our code is
          going to be running hundreds of times each second so every
          little bit helps!

          Note that the biggest performance gain here, by far, comes
          from not having to run through the getPosition function
          hundreds of times.
          */
          setAttribute('startWidth', parseInt(offsetWidth));
          setAttribute('startHeight', parseInt(offsetHeight));
          setAttribute('startLeft', pos.x);
          setAttribute('startTop', pos.y);
        }

        // loop through each child element of each container
        for(var j=0; j<dragConts[i].childNodes.length; j++){
          with(dragConts[i].childNodes[j]){
            if((nodeName=='#text') || (dragConts[i].childNodes[j]==curTarget)) continue;

            var pos = getPosition(dragConts[i].childNodes[j]);

            // save the width, height and position of each element
            setAttribute('startWidth', parseInt(offsetWidth));
            setAttribute('startHeight', parseInt(offsetHeight));
            setAttribute('startLeft', pos.x);
            setAttribute('startTop', pos.y);
          }
        }
      }
    }
  }

  // If we get in here we are dragging something
  if(curTarget){
    // move our helper div to wherever the mouse is (adjusted by mouseOffset)
    dragHelper.style.top = mousePos.y - mouseOffset.y;
    dragHelper.style.left = mousePos.x - mouseOffset.x;

    var dragConts = DragDrops[curTarget.getAttribute('DragObj')];
    var activeCont = null;

    var xPos = mousePos.x - mouseOffset.x + (parseInt(curTarget.getAttribute('startWidth')) /2);
    var yPos = mousePos.y - mouseOffset.y + (parseInt(curTarget.getAttribute('startHeight'))/2);

    // check each drop container to see if our target object is "inside" the container
    for(var i=0; i<dragConts.length; i++){
      with(dragConts[i]){
        if(((getAttribute('startLeft')) < xPos) &&
          ((getAttribute('startTop')) < yPos) &&
          ((getAttribute('startLeft') + getAttribute('startWidth')) > xPos) &&
          ((getAttribute('startTop') + getAttribute('startHeight')) > yPos)){

            /*
            our target is inside of our container so save the container into
            the activeCont variable and then exit the loop since we no longer
            need to check the rest of the containers
            */
            activeCont = dragConts[i];

            // exit the for loop
            break;
        }
      }
    }

    // Our target object is in one of our containers. Check to see where our div belongs
    if(activeCont){
      // beforeNode will hold the first node AFTER where our div belongs
      var beforeNode = null;

      // loop through each child node (skipping text nodes).
      for(var i=activeCont.childNodes.length-1; i>=0; i--){
        with(activeCont.childNodes[i]){
          if(nodeName=='#text') continue;

          // if the current item is "After" the item being dragged
          if(
            curTarget != activeCont.childNodes[i] &&
            ((getAttribute('startLeft') + getAttribute('startWidth')) > xPos) &&
            ((getAttribute('startTop') + getAttribute('startHeight')) > yPos)){
              beforeNode = activeCont.childNodes[i];
          }
        }
      }

      // the item being dragged belongs before another item
      if(beforeNode){
        if(beforeNode!=curTarget.nextSibling){
          activeCont.insertBefore(curTarget, beforeNode);
        }

      // the item being dragged belongs at the end of the current container
      } else {
        if((curTarget.nextSibling) || (curTarget.parentNode!=activeCont)){
          activeCont.appendChild(curTarget);
        }
      }

      // make our drag item visible
      if(curTarget.style.display!=''){
        curTarget.style.display = '';
      }
    } else {

      // our drag item is not in a container, so hide it.
      if(curTarget.style.display!='none'){
        curTarget.style.display = 'none';
      }
    }
  }

  // track the current mouse state so we can compare against it next time
  lMouseState = iMouseDown;

  // mouseMove target
  lastTarget = target;

  // track the current mouse state so we can compare against it next time
  lMouseState = iMouseDown;

  // this helps prevent items on the page from being highlighted while dragging
  return false;
}

function mouseUp(ev){
  if(curTarget){
    // hide our helper object - it is no longer needed
    dragHelper.style.display = 'none';

    // if the drag item is invisible put it back where it was before moving it
    if(curTarget.style.display == 'none'){
      if(rootSibling){
        rootParent.insertBefore(curTarget, rootSibling);
      } else {
        rootParent.appendChild(curTarget);
      }
    }

    // make sure the drag item is visible
    curTarget.style.display = '';
  }
  curTarget = null;
  iMouseDown = false;
}

function mouseDown(){
  iMouseDown = true;
  if(lastTarget){
    return false;
  }
}

document.onmousemove = mouseMove;
document.onmousedown = mouseDown;
document.onmouseup = mouseUp;

window.onload = function(){
  // Create our helper object that will show the item while dragging
  dragHelper = document.createElement('DIV');
  dragHelper.style.cssText = 'position:absolute;display:none;';

  CreateDragContainer(
    document.getElementById('DragContainer1'),
    document.getElementById('DragContainer2'),
    document.getElementById('DragContainer3')
  );

  document.body.appendChild(dragHelper);
}

</script>

<!--the mouse over and dragging class are defined on each item-->

<div class="DragContainer" id="DragContainer1">
  <div class="DragBox" id="Item1" overClass="OverDragBox" dragClass="DragDragBox">Item #1</div>
  <div class="DragBox" id="Item2" overClass="OverDragBox" dragClass="DragDragBox">Item #2</div>
  <div class="DragBox" id="Item3" overClass="OverDragBox" dragClass="DragDragBox">Item #3</div>
  <div class="DragBox" id="Item4" overClass="OverDragBox" dragClass="DragDragBox">Item #4</div>
</div>
<div class="DragContainer" id="DragContainer2">
  <div class="DragBox" id="Item5" overClass="OverDragBox" dragClass="DragDragBox">Item #5</div>
  <div class="DragBox" id="Item6" overClass="OverDragBox" dragClass="DragDragBox">Item #6</div>
  <div class="DragBox" id="Item7" overClass="OverDragBox" dragClass="DragDragBox">Item #7</div>
  <div class="DragBox" id="Item8" overClass="OverDragBox" dragClass="DragDragBox">Item #8</div>
</div>
<div class="DragContainer" id="DragContainer3">
  <div class="DragBox" id="Item9" overClass="OverDragBox" dragClass="DragDragBox">Item #9</div>
  <div class="DragBox" id="Item10" overClass="OverDragBox" dragClass="DragDragBox">Item #10</div>
  <div class="DragBox" id="Item11" overClass="OverDragBox" dragClass="DragDragBox">Item #11</div>
  <div class="DragBox" id="Item12" overClass="OverDragBox" dragClass="DragDragBox">Item #12</div>
</div>

Javascript 相关文章推荐
在b/s开发中经常用到的javaScript技术
Aug 23 Javascript
由点击页面其它地方隐藏div所想到的jQuery的delegate
Aug 29 Javascript
js post提交调用方法
Feb 12 Javascript
JavaScript中关于for循环删除数组元素内容时出现的问题
Nov 21 Javascript
使用grunt合并压缩js和css文件的方法
Mar 02 Javascript
让bootstrap的carousel支持滑动滚屏的实现代码
Nov 27 Javascript
详解通过源码解析Node.js中cluster模块的主要功能实现
May 16 Javascript
vue移动端下拉刷新和上拉加载的实现代码
Sep 08 Javascript
谈谈React中的Render Props模式
Dec 06 Javascript
vue实现数字动态翻牌的效果(开箱即用)
Dec 08 Javascript
2020京东618叠蛋糕js脚本(亲测好用)
Jun 02 Javascript
vue项目开启Gzip压缩和性能优化操作
Oct 26 Javascript
拖动一个HTML元素
Dec 22 #Javascript
JavaScript中Array 对象相关的几个方法
Dec 22 #Javascript
JavaScript事件列表解说
Dec 22 #Javascript
改进:论坛UBB代码自动插入方式
Dec 22 #Javascript
用javascript获取地址栏参数
Dec 22 #Javascript
在IE下:float属性会影响offsetTop的取值
Dec 22 #Javascript
Javascript实现的分页函数
Dec 22 #Javascript
You might like
支持php4、php5的mysql数据库操作类
2008/01/10 PHP
php实现图形显示Ip地址的代码及注释
2014/01/20 PHP
PHP实现通过正则表达式替换回调的内容标签
2015/06/15 PHP
PHP代码判断设备是手机还是平板电脑(两种方法)
2015/10/19 PHP
PHP convert_cyr_string()函数讲解
2019/02/13 PHP
一个用js实现的页内搜索代码
2007/05/23 Javascript
基于JQuery.timer插件实现一个计时器
2010/04/25 Javascript
利用jQuery操作对象数组的实现代码
2011/04/27 Javascript
javascript suggest效果 自动完成实现代码分享
2012/02/17 Javascript
Javascript判断对象是否相等实现代码
2013/03/18 Javascript
jQuery jcrop插件截图使用方法
2013/11/20 Javascript
js四舍五入数学函数round使用实例
2014/05/09 Javascript
js函数内变量的作用域分析
2015/01/12 Javascript
JavaScript实现找质数代码分享
2015/03/24 Javascript
jQuery选择器源码解读(三):tokenize方法
2015/03/31 Javascript
jquery表单插件Autotab使用方法详解
2016/06/24 Javascript
基于Vue过渡状态实例讲解
2017/09/14 Javascript
jquery中done和then的区别(详解)
2017/12/19 jQuery
Vue2.0 v-for filter列表过滤功能的实现
2018/09/07 Javascript
vue实现form表单与table表格的数据关联功能示例
2019/01/29 Javascript
VUE-ElementUI 自定义Loading图操作
2020/11/11 Javascript
[01:02:20]Mineski vs TNC 2019国际邀请赛小组赛 BO2 第二场 8.15
2019/08/16 DOTA
python中getaddrinfo()基本用法实例分析
2015/06/28 Python
python使用threading获取线程函数返回值的实现方法
2017/11/15 Python
Python异步操作MySQL示例【使用aiomysql】
2019/05/16 Python
解决python中导入win32com.client出错的问题
2019/07/26 Python
Python序列类型的打包和解包实例
2019/12/21 Python
PyCharm2020.1.1与Python3.7.7的安装教程图文详解
2020/08/07 Python
了解一下python内建模块collections
2020/09/07 Python
美国玛丽莎收藏奢华时尚商店:Marissa Collections
2016/11/21 全球购物
英国图书音像网站:Hive.co.uk(图书、电子书、DVD、蓝光、音乐CD等)
2017/10/16 全球购物
美国职棒大联盟的官方手套、球和头盔:Rawlings
2020/02/15 全球购物
经理助理岗位职责
2015/02/02 职场文书
文艺委员竞选稿
2015/11/19 职场文书
公司财务制度:成本管理控制制度模板
2019/11/19 职场文书
腾讯云服务器部署前后分离项目之前端部署
2022/06/28 Servers