代码改变世界

一个DIV拖放的案例

2013-06-07 14:01  Evan.Pei  阅读(307)  评论(0编辑  收藏  举报

2013/6/6-2013/6/7研究心得记录一下

效果图:

一.aspx页面

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
    <link href="Style1.css" type="text/css" rel="stylesheet" />
    <script src="jq/JScript3.js" type="text/javascript"></script>
    <script src="jq/JScript1.js" type="text/javascript"></script>
    <script src="jq/jquery-1.3.2.js" type="text/javascript">
    </script>
</head>
<body onload="PageLoad(4,6);"> 
        <div id='div_Content' style=" text-align:center;">   
        </div>
</body>
</html>
<script type="text/javascript">
    setTimeout(a,100);
    function a(){
        $('#m_1_5').css('height', '200px');
        $('#m_2_5').css('height', '200px');
        $('#m_3_5').css('height', '200px');
    }
</script>

 二。style1.css

body {   
width:100%;   
max-height:100%;   
padding:0px;   
margin:0px;   
text-align:center;   
}   
.cell {   
float:left;    /*float 属性定义元素在哪个方向浮动*/ 
clear:right;   /*clear 属性规定元素的哪一侧不允许其他浮动元素*/
}   
  
.row {   
clear:both;  /*在左右两侧均不允许浮动元素*/   
}   
  
.r_nbsp {   
/*width:200px;   */
}   
  
.root {   
/*width:1010px;*/
/*margin: 0 auto;   /*margin 简写属性在一个声明中设置所有外边距属性*/
}   
  
.root * {   
/*次属性FF的说*/  
-moz-user-select:none;   
}   
  
.line {   
width:202px;
line-height:20px;   
height:20px;   
overflow:hidden;   
font-size:12px;   
}   
  
.move {   
border:#CCCCCC 1px solid;   
width:200px;   
/*height:20px;*/   
}   
  
.title {   
cursor:move;   
/*background:#0080C0;*/   
font-size:13px;   
font-weight:bold;   
color:#FFFFFF;   
line-height:24px;   
text-align:center;   
}   
  
.content {   
border-top:#CCCCCC 1px solid;   
 
background-color:#F7F7F7;   
}   
  
.CDrag_temp_div {   
border:orange 1px dashed;   
} 

 三。JScript1.js

//var div1 = null;
//var div2 = null;

var Class =
{
    //创建类   
    create: function() {
        return function() {
            this.initialize.apply(this, arguments);
        };
    }
};

var $A = function(a) {
    //转换数组   
    return a ? Array.apply(null, a) : new Array;
};

var $$ = function(id) {
    //获取对象   
    return document.getElementById(id);
};

Object.extend = function(a, b) {
    //追加方法   
    for (var i in b) a[i] = b[i];
    return a;
};

Object.extend(Object, {
    addEvent: function(a, b, c, d) {
        //添加函数   
        if (a.attachEvent) a.attachEvent(b[0], c); //attachEvent("onclick", buttonClicked);   //给按钮增加事件   
        else a.addEventListener(b[1] || b[0].replace(/^on/, ""), c, d || false);
        return c;
    },

    delEvent: function(a, b, c, d) {
        if (a.detachEvent) a.detachEvent(b[0], c);
        else a.removeEventListener(b[1] || b[0].replace(/^on/, ""), c, d || false);
        return c;
    },
    //---------------------------------------获取Event  
    reEvent: function() {
        //获取Event   
        return window.event ? window.event : (function(o) {
            do {
                o = o.caller;
            } while (o && !/^\[object[ A-Za-z]*Event\]$/.test(o.arguments[0]));
            return o.arguments[0];
        })(this.reEvent);
    }

});

Function.prototype.bind = function() {
    //绑定事件   
    var wc = this, a = $A(arguments), o = a.shift();
    return function() {
        wc.apply(o, a.concat($A(arguments)));
    };
};

/////////////////////////////////////////////////////////////  
var Table = Class.create();
Table.prototype = {
    //---------------------------------------初始化  
    initialize: function() {
        //初始化   
        var wc = this;
        wc.cols = new Array; //创建列   
    },


    //---------------------------------------添加列  
    addCols: function(o) //o代表列
    {
        //添加列   
        var wc = this,
		cols = wc.cols,
		i = cols.length;
        return cols[i] = {
            id: i, div: o, rows: new Array, //创建行   
            addRow: wc.addRow,
            chRow: wc.chRow,
            inRow: wc.inRow,
            delRow: wc.delRow
        };
    },


    //---------------------------------------添加行   
    addRow: function(o) {
        //添加行   
        var wc = this,
		rows = wc.rows,
		i = rows.length;
        return rows[i] = {
            id: i, div: o, cols: wc
        };
    },


    //---------------------------------------插入行   
    inRow: function(a, b) {
        //插入行   
        var wc = b.cols = this,
		    rows = wc.rows, i;
        if (a < rows.length) {
            for (i = a; i < rows.length; i++)
                rows[i].id++;
            rows.splice(a, 0, b);
            b.id = a;
            return b;
        }
        else {
            b.id = rows.length;
            return rows[b.id] = b;
        }
    },


    //---------------------------------------删除列 
    delRow: function(a) {
        //删除列   
        var wc = this,
		rows = wc.rows,
		i, r;
        if (a >= rows.length) return;
        r = rows[a];
        rows.splice(a, 1);
        for (i = a; i < rows.length; i++) rows[i].id = i;
        return r;
    }
};

//////////////////////////////////////////////////////////////
var CDrag = Class.create();
CDrag.IE = /MSIE/.test(window.navigator.userAgent);
CDrag.prototype = {
    //---------------------------------------初始化成员  
    initialize: function() {
        //初始化成员   
        var wc = this; //this指类CDrag
        wc.table = new Table; //建立表格对象 ,wc.table属性的值是Table类
        wc.iFunc = null;
        wc.eFunc = null; //新建两个属性值都为空
        wc.obj = {//wc.obj属性是对象
            on: { a: null, b: "" },
            row: null, left: 0, top: 0
        };

        wc.temp = { row: null, div: document.createElement("div") }; //wc.temp对象
        wc.temp.div.setAttribute(CDrag.IE ? "className" : "class", "CDrag_temp_div"); //根据浏览器设置div类样式 ,wc.temp对象中的div属性
        wc.temp.div.innerHTML = "<div id='vv' style='position:absolute;'> </div>"; //将内容设置为空
        wc.temp.div.style.textAlign = "left"; ////////////+
    },

    //---------------------------------------获取鼠标位置,鼠标单击层时触发,该方法返回鼠标的xy轴的位置 
    reMouse: function(a) {
        //获取鼠标位置   
        var e = Object.reEvent(); //被单击的层
        return {
            x: document.documentElement.scrollLeft + e.clientX, //获取鼠标单击X轴的位置   
            y: document.documentElement.scrollTop + e.clientY  //获取鼠标单击Y轴的位置 
        };
    },



    //---------------------------------------获取元素绝对位置    
    rePosition: function(o) {  //参数是div 
        //获取元素绝对位置   
        var $x = $y = 0;
        do {
            $x += o.offsetLeft;
            $y += o.offsetTop;
        } while ((o = o.offsetParent) && o.tagName != "BODY");
        return { x: $x, y: $y };
    },


    //---------------------------------------单击行时触发
    sMove: function(o) {
        //当拖动开始时设置参数   
        var wc = this;
        if (wc.iFunc || wc.eFinc) return;
        var mouse = wc.reMouse(), //调用方法获取鼠标的位置
				temp = wc.temp, //对象
				div = o.div, //当前活动的DIV
				position = wc.rePosition(div); //获取该活动的DIV的xy的位置

        obj = wc.obj, //对象,现在是空的,用来记录活动的层的信息
				obj.row = o; //o是addRow返回的对象
        obj.on.b = "me";
        obj.left = mouse.x - position.x;   //赋值,鼠标的位置-层的位置 X
        obj.top = mouse.y - position.y;
        temp.row = document.body.appendChild(div.cloneNode(true)); //复制预拖拽对象,克隆div 

        //------1
        with (temp.row.style) {//设置被拖拽DIV的样式
            //设置复制对象
            position = "absolute"; //设置绝对位置
            left = mouse.x - obj.left + "px";
            top = mouse.y - obj.top + "px";
            zIndex = 100;
            opacity = "0.3";
            filter = "alpha(opacity:50)"; //透明
        }
        //-------2 
        with (temp.div.style) {//div的高度和宽度,空div的样式
            //设置站位对象
            height = div.clientHeight + "px";
            width = div.clientWidth + "px";
            //background = "Orange";//占位背景色
        }
        //------3
        /*div.parentNode.insertBefore(temp.div, div);  
        div.style.display = "none"; //隐藏预拖拽对象*/
        div.parentNode.replaceChild(temp.div, div); //新的DIV替换了之前的div  
        //------4
        wc.iFunc = Object.addEvent(document, ["onmousemove"], wc.iMove.bind(wc)); //开始拖动时的事件,addEvent添加事件,addEvent( object, eventType, function );    
        wc.eFunc = Object.addEvent(document, ["onmouseup"], wc.eMove.bind(wc));  //鼠标释放的事件
        document.onselectstart = new Function("return false"); //鼠标单击后不能做任何事
        //------5
    },



    //---------------------------------------当鼠标移动时设置参数  
    iMove: function() {
        //当鼠标移动时设置参数   
        var wc = this, //this=CDrag
						cols = wc.table.cols, //获取当前的列数
						mouse = wc.reMouse(), //鼠标的位置
						obj = wc.obj, //对象,记录着活动的层的信息
						temp = wc.temp,
						row = obj.row, //
						div = temp.row, //克隆后的div   
						t_position,
						t_cols,
						t_rows,
						i,
						j;
        //设置div随着鼠标移动  
        with (div.style) {
            left = mouse.x - obj.left + "px";
            top = mouse.y - obj.top + "px";
        }
        //循环所有列
        for (i = 0; i < cols.length; i++) {
            t_cols = cols[i]; //当前列
            t_position = wc.rePosition(t_cols.div); //获取整列div元素的位置  
            //确保鼠标在这几列的范围内移动
            if (t_position.x < mouse.x && t_position.x + t_cols.div.offsetWidth > mouse.x)//div的x小于鼠标的x && 元素x+
            {
                if (t_cols.rows.length > 0) {
                    //如果此列行数大于0   
                    if (wc.rePosition(t_cols.rows[0].div).y + 20 > mouse.y) //第一列的高度+20>鼠标的高度
                    {
                        //alert(wc.rePosition(t_cols.rows[0].div).y+'鼠标y:'+mouse.y);
                        //如果鼠标位置大于第一行的位置即是最上。。   
                        //向上   
                        obj.on.a = t_cols.rows[0]; //列里面的第一行   
                        obj.on.b = "up";
                        obj.on.a.div.parentNode.insertBefore(temp.div, obj.on.a.div);
                        //temp.div(之前创建的空div),obj.on.a.div(最上面的div)先获取父节点m_1,m_2,在将其添加到最前面  
                        //oNewNode :  必选项。对象(Element)。要被插入文档结构的对象。
                        //oChildNode :  可选项。对象(Element)。定位插入点。 oNewNode 被插入到紧贴这个子对象的前面 
                    }
                    //此列的行数大于一        第一行就是被克隆的那行   只要鼠标移过第二行
                    else if (t_cols.rows.length > 1 && t_cols.rows[0] == row && wc.rePosition(t_cols.rows[1].div).y + 20 > mouse.y) {
                        //如果第一行是拖拽对象而第鼠标大于第二行位置则,没有动。。   
                        //向上   
                        obj.on.b = "me";
                        t_cols.rows[1].div.parentNode.insertBefore(temp.div, t_cols.rows[1].div);
                    }
                    else {      //循环所有列的行
                        for (j = t_cols.rows.length - 1; j > -1; j--) {
                            //重最下行向上查询   
                            t_rows = t_cols.rows[j];
                            if (t_rows == obj.row) { continue; } //如果是同一行 

                            if (wc.rePosition(t_rows.div).y < mouse.y) {
                                //如果鼠标大于这行则在这行下面   
                                if (t_rows.id + 1 < t_cols.rows.length && t_cols.rows[t_rows.id + 1] != obj.row) {
                                    //如果这行有下一行则重这行下一行的上面插入   
                                    t_cols.rows[t_rows.id + 1].div.parentNode.
																																						insertBefore(temp.div, t_cols.rows[t_rows.id + 1].div);
                                    obj.on.a = t_rows;
                                    obj.on.b = "down";
                                }
                                else if (t_rows.id + 2 < t_cols.rows.length) {
                                    //如果这行下一行是拖拽对象则插入到下两行,即拖拽对象返回原位   
                                    t_cols.rows[t_rows.id + 2].div.parentNode.
																																						insertBefore(temp.div, t_cols.rows[t_rows.id + 2].div);
                                    obj.on.b = "me";
                                }
                                else {
                                    //前面都没有满足则放在最低行   
                                    t_rows.div.parentNode.appendChild(temp.div);
                                    obj.on.a = t_rows;
                                    obj.on.b = "down";
                                }
                                return;
                            }
                        }
                    }
                }
                else {
                    //此列无内容添加新行   
                    t_cols.div.appendChild(temp.div);
                    obj.on.a = t_cols;
                    obj.on.b = "new";
                }
            }
        }
    },
    //---------------------------------------当鼠标释放时设置参数
    eMove: function() {
        //当鼠标释放时设置参数   
        var wc = this,
			obj = wc.obj, //记录正活动div的信息
			temp = wc.temp,
			row = obj.row,
			div = row.div, //拖动的div
			o_cols,
			n_cols;
        div1 = temp.row;
        div2 = temp.div; //占位div
        //alert(temp.row.offsetTop + ',' + zhanwei.offsetTop);(temp.row,zhanwei)
        var div2_y = div2.offsetTop;
        var div2_x = document.getElementById('vv').offsetLeft; //div2.offsetLeft;

        var div1_Id = div1.id;
        Object.delEvent(document, ["onmousemove"], wc.iFunc);
        $("#" + div1_Id).animate({ left: div2_x, top: div2_y }, function() {
            if (obj.on.b == "up") {
                //向最上添加   
                o_cols = obj.row.cols;
                n_cols = obj.on.a.cols;
                n_cols.inRow(0, o_cols.delRow(obj.row.id));
            }
            else if (obj.on.b == "down") {
                //相对向下添加   
                o_cols = obj.row.cols;
                n_cols = obj.on.a.cols;
                n_cols.inRow(obj.on.a.id + 1, o_cols.delRow(obj.row.id));
            }
            else if (obj.on.b == "new") {
                //向无内容列添加   
                o_cols = obj.row.cols;
                n_cols = obj.on.a;
                n_cols.inRow(0, o_cols.delRow(obj.row.id));
            }
            temp.div.parentNode.replaceChild(div, temp.div); //div替换temp.div
            temp.row.parentNode.removeChild(temp.row);
            delete temp.row;
            //Object.delEvent(document, ["onmousemove"], wc.iFunc);
            Object.delEvent(document, ["onmouseup"], wc.eFunc);
            document.onselectstart = wc.iFunc = wc.eFunc = null;

        });
        //        oTimer = setInterval(
        //           function() {
        //               var isContinue = false;
        //               var div1_y = div1.offsetTop;
        //               var div1_x = div1.offsetLeft;
        //               var div2_y = div2.offsetTop;
        //               var div2_x = document.getElementById('vv').offsetLeft; //div2.offsetLeft;
        //               var x1 = 0;
        //               var y1 = 0;

        //               if (div1_x > div2_x) {
        //                   if (div1_x - div2_x <= 20) {
        //                       div1.style.left = div1.offsetLeft - 1 + "px"; isContinue = true;
        //                   } else {
        //                       div1.style.left = div1.offsetLeft - 20 + "px"; isContinue = true;
        //                   }
        //               } else if (div1_x < div2_x) {
        //                   if (div2_x - div1_x <= 20) {
        //                       div1.style.left = div1.offsetLeft + 1 + "px"; isContinue = true;
        //                   } else {
        //                       div1.style.left = div1.offsetLeft + 20 + "px"; isContinue = true;
        //                   }
        //               }
        //               if (div1_y > div2_y) {
        //                   if (div1_y - div2_y <= 20) {
        //                       div1.style.top = div1.offsetTop - 1 + "px"; isContinue = true;
        //                   } else {
        //                       div1.style.top = div1.offsetTop - 20 + "px"; isContinue = true;
        //                   }
        //               } else if (div1_y < div2_y) {
        //                   if (div2_y - div1_y <= 20) {
        //                       div1.style.top = div1.offsetTop + 1 + "px"; isContinue = true;
        //                   } else {
        //                       div1.style.top = div1.offsetTop + 20 + "px"; isContinue = true;
        //                   }
        //               }
        //               if (!isContinue) {
        //                   window.clearInterval(oTimer);
        //                   if (obj.on.b == "up") {
        //                       //向最上添加   
        //                       o_cols = obj.row.cols;
        //                       n_cols = obj.on.a.cols;
        //                       n_cols.inRow(0, o_cols.delRow(obj.row.id));
        //                   }
        //                   else if (obj.on.b == "down") {
        //                       //相对向下添加   
        //                       o_cols = obj.row.cols;
        //                       n_cols = obj.on.a.cols;
        //                       n_cols.inRow(obj.on.a.id + 1, o_cols.delRow(obj.row.id));
        //                   }
        //                   else if (obj.on.b == "new") {
        //                       //向无内容列添加   
        //                       o_cols = obj.row.cols;
        //                       n_cols = obj.on.a;
        //                       n_cols.inRow(0, o_cols.delRow(obj.row.id));
        //                   }
        //                   temp.div.parentNode.replaceChild(div, temp.div); //div替换temp.div
        //                   temp.row.parentNode.removeChild(temp.row);
        //                   delete temp.row;
        //                   Object.delEvent(document, ["onmousemove"], wc.iFunc);
        //                   Object.delEvent(document, ["onmouseup"], wc.eFunc);
        //                   document.onselectstart = wc.iFunc = wc.eFunc = null;
        //               }
        //           }

        //        , 50);






    },


    //---------------------------------------添加对象    
    add: function(o) {  //o代表addRow返回的对象
        //添加对象   
        //alert(o.div);
        var wc = this;
        Object.addEvent(o.div.childNodes[CDrag.IE ? 0 : 1], ["onmousedown"], wc.sMove.bind(wc, o));
    },


    //---------------------------------------初始化成员 
    parse: function(o)//o代表数组
    {
        //初始化成员   
        var wc = this, //这里所有的this指向的是对象CDrag 
				table = wc.table,
				cols,
				i, j;
        for (i = 0; i < o.length; i++)//根据对象数组循环列数
        {
            cols = table.addCols(o[i].cols); //添加列
            for (j = 0; j < o[i].rows.length; j++)
                wc.add(cols.addRow(o[i].rows[j])); //将行添加到列中,并绑上事件  
        }
    }
};
}

 四。JScript3.js

//窗体加载事件
function PageLoad(colNumber, rowNumber) {

    var dwidth = 0;
    for (var w = 0; w < colNumber - 1; w++) {//根据列数判断div的宽度
        dwidth = dwidth + 202; //每多一列宽度加202
    }
    $$("div_Content").style.width = dwidth + 'px';



    var Cwidth = 0; //列宽
    for (var i = 1; i < colNumber; i++) {
        var div = CreateObj('div');
        div.id = 'm_' + i; //id
        div.style.padding = "5";
        div.setAttribute('className', 'cell'); //样式
        var CTitle = CreateObj('div');
        CTitle.setAttribute('className', 'line'); //列
        CTitle.innerText = '第' + i + '列';
        div.appendChild(CTitle); //添加头
        for (var j = 1; j < rowNumber; j++) {
            var DContent = CreateObj('div');
            DContent.setAttribute('className', 'move');
            DContent.id = 'm_' + i + '_' + j;
            DContent.style.background = "#fff";
            var title = CreateObj('div');
            title.setAttribute('className', 'title');
            title.innerText = '第' + i + '列的第' + j + '个说';
            title.id = "tit_" + i + "_" + j;
            //title.style.height = "200px";
            //设置宽度随内容变化
            if (j == 1 && (title.innerText.length) < 10) {
                Cwidth = 200;
            }
            else if (j == 1 && (title.innerText.length) > 10) {//根据内容的长度绝对div的宽度
                var wNumber = (title.innerText.length) - 10;
                Cwidth = (200 + (wNumber * 10));
            }
            with (title.style) {//设置div宽度
                width = Cwidth + 'px';
                height = "30px";
                background = '#0080C0';
            }
            DContent.style.width = Cwidth + 'px';
            DContent.style.height = '100px';
            //DContent.innerText = "fdsfds";
            var neirongdiv = CreateObj("div");
            neirongdiv.innerText = "fdsfdsfdsfsd";
            DContent.appendChild(title);
            DContent.appendChild(neirongdiv);
            div.appendChild(DContent); //将行添加到列中
        }
        div.style.width = Cwidth + 'px'; //设置大div的宽度也随着内容改变
        with (CTitle.style) {
            width = 10 + Cwidth + 'px';
        }
        $$("div_Content").appendChild(div);
    }

    //拼接数组对象
    var F_Node = $$("div_Content")//获取最外面的层
    var nodes = F_Node.childNodes;
    //循环子节点
    var strs = '[';
    for (var i = 0; i < nodes.length; i++) {
        strs = strs + "{cols:$$('" + nodes[i].id + "')";
        var node2 = nodes[i].childNodes; //获取子节点
        if (node2.length > 0)
            strs += ",rows:[";
        for (var j = 0; j < node2.length; j++) {
            var CurrentNode = node2[j].nextSibling; //兄弟节点的下一个节点
            if (CurrentNode != null)
                strs += "$$('" + CurrentNode.id + "'),"
        }
        strs = strs.substring(0, strs.length - 1) + "]},"; //去,号
    }
    strs = strs.substring(0, strs.length - 1) + "]";

    var wc = new CDrag;
    wc.parse(eval(strs));
}
//创建对象
function CreateObj(obj) {
    return document.createElement(obj);
}