RT:网上代码太复杂了 求一精简的 div拖拽  cookie保存拖拽后位置<div id="block1" style="width:110px;height:128px;top:96px;left:1px;position:absolute;container: positioned;">
<a href="http://www.baidu.com" target="_blank">
<img src='images/books.jpg' />
</a>
</div>

解决方案 »

  1.   


    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title> 拖拽+COOKIE保存</title>
    <meta http-equiv="Content-Type" content="text/html;charset=gb2312" />
    <style type="text/css">
    *{font-size:12px}
    /*样式class*/
    .dragTable{
    font-size:12px;
    border-top:1px solid #3366cc;
    margin-bottom: 10px;
    width:100%;
    background-color:#FFFFFF;
    }
    .dragTR{
    cursor:move;/* 控制当鼠标移动到该行上时显示的样式*/
    color:#7787cc;
    background-color:#e5eef9;
    font-size:16px;
    font- family:"宋体";
    font-weight:bold;
    letter-spacing:1px;
    }
    /*利用 tagName定义样式*/
    td{vertical-align:top;}
    /*#表示对id=parentTable元素的样式定义* /
    #parentTable{
    border-collapse:collapse;
    letter-spacing:25px;
    }
    </style><script language ="javascript" type="text/javascript">
    //---- 设置Cookie------function setCookie(name,value,domain){var value = escape(value);var nameString = "Drag_"+name + "=" + value; //给cookie变量增加前缀var extime = new Date();extime.setTime (extime.getTime () + 315360000);var expiryString = ";expires=" + extime.toGMTString();var domainString = "";var pathString = ";path=/";var setvalue = nameString + expiryString;document.cookie = setvalue;
    }//----设置 Cookie 结束------//---读取Cookie-------function getcookie (name)
    {
    var CookieFound = false;
    var start = 0;
    var end = 0;
    var CookieString = document.cookie;var i = 0;
    name="Drag_"+name; //增加前缀
    while (i <= CookieString.length)
    {
    start = i ;
    end = start + name.length;
    if (CookieString.substring(start, end) == name)
    {
    CookieFound = true;
    break;
    }
    i++;
    }if (CookieFound)
    {
    start = end + 1;
    end = CookieString.indexOf(";",start);
    if (end < start)
    end = CookieString.length;
    var getvalue = CookieString.substring(start, end);
    return unescape(getvalue);
    }
    return "";
    }//--- 读取Cookie 结束-------//检测是否禁用了cookie
    function isEnableCookie() {
    try {
    var cookie_helper = new CookieHelper("");
    var test_cookie_name = "test_cookie_name";
    var test_cookie_value = "test_cookie_value";
    var test_cookie_value_ret = "";cookie_helper.writeCookie(test_cookie_name,test_cookie_value);
    test_cookie_value_ret = cookie_helper.getCookieValue(test_cookie_name);if ( test_cookie_value_ret != null ) {
    cookie_helper.removeCookie(test_cookie_name);
    return true;
    } else {
    return false;
    }
    } catch (error) {
    return false;
    }
    }
    </script>
    </head>
    <body>
    <table border="0" cellpadding="0" cellspacing="10" width="950" id="parentTable">
    <tr >
    <td width="350" valign="top">
    <table id ="st1" border=1 class="dragTable" cellspacing="0">
    <tr><td>图片一</td></tr>
    <tr><td id="div1"><img src="http://b10.photo.store.qq.com/http_imgload.cgi?/rurl4_b=918a7e3a6f95de5540355f0c5e1d571e956e0a263268886c642dd852e94f04473e0a752eec41bd1abd67504bcddcc43268c145cd4dcd27c20bc4ed05c205883135f51c08a0bdbd9562a7980ba773b0596210353b&amp;a=24&amp;b=10" /></td></tr>
    </table>
    <table style="display:none" class="dragTable"><tr><td></td></tr></table>
    <table id="st2" border=1 class="dragTable" cellspacing="0">
    <tr><td>div2</td></tr>
    <tr><td id="div2"></td></tr>
    </table></div></td>
    <td width="350">
    <table id="st3" border=1 class="dragTable" cellspacing="0">
    <tr><td>div3</td></tr>
    <tr><td id="div3"></td></tr>
    </table>
    <table style="display:none" class="dragTable"><tr><td></td></tr></table>
    <table id="st4" border=1 class="dragTable" cellspacing="0">
    <tr><td>div4</td></tr>
    <tr><td id="div4" ></td></tr>
    </table></td>
    <td width="350">
    <table id="st5" border=1 class="dragTable" cellspacing="0">
    <tr><td>div5</td></tr>
    <tr><td id="div5"></td></tr>
    </table>
    <table style="display:none" class="dragTable"><tr><td></td></tr></table>
    <table id="st6" border=1 class="dragTable" cellspacing="0">
    <tr><td>div6</td></tr>
    <tr align=center>
    <td id="div6">
    <table cellSpacing=0 cellPadding=0 border=0 >
    <tr>
    <td align=center></td>
    </tr>
    </table>
    </td></tr>
    </table>
    <table style="display:none" class="dragTable" ID="Table1"><tr><td></td></tr></table>
    <table id="st7" border=1 class="dragTable" cellspacing="0">
    <tr><td>div7</td></tr>
    <tr><td id="div7">
    <table cellSpacing=0 cellPadding=0 width=260 border=0 ID="Table2">
    <tr>
    <td align="center">
    </td>
    </tr>
    </table>
    </td>
    </tr>
    </table>
    </td>
    </tr>
    </table> <script language="javascript" type="text/javascript">/*
    实现拖拽的代码
    */
    var draged=false;
    tdiv=null;
    function dragStart(){
    ao=event.srcElement; //设置或获取触发事件的对象,这里是可以移动的table对象的TD对象
    if((ao.tagName=="TD")||(ao.tagName=="TR"))
    ao=ao.offsetParent; //获取定义对象offsetTop和offsetLeft属性的容器对象的引用,这里是获取的被移动的table对象。
    else
    return;
    draged=true;
    tdiv=document.createElement("div");
    tdiv.innerHTML=ao.outerHTML;
    tdiv.style.display="block";
    tdiv.style.position="absolute";
    tdiv.style.filter="alpha(opacity=70)";
    tdiv.style.cursor="move";
    tdiv.style.width=ao.offsetWidth; //被移动table对象的高度
    tdiv.style.height=ao.offsetHeight;
    tdiv.style.top=getInfo(ao).top;
    tdiv.style.left=getInfo(ao).left;
    document.body.appendChild(tdiv);
    lastX=event.clientX;
    lastY=event.clientY;
    lastLeft=tdiv.style.left;
    lastTop=tdiv.style.top;
    try{
    ao.dragDrop(); //初始化拖曳事件
    }catch(e)
    {}
    }
    function draging(){//重要:判断MOUSE的位置
    if(!draged)return;
    var tX=event.clientX;
    var tY=event.clientY;
    tdiv.style.left=parseInt(lastLeft)+tX-lastX;//
    tdiv.style.top=parseInt(lastTop)+tY-lastY;
    for(var i=0;i<parentTable.cells.length;i++){//for1
    var parentCell=getInfo(parentTable.cells[i]);
    //判断鼠标的位置是否移动到父表的某个列中
    if(tX>=parentCell.left&&tX<=parentCell.right&&tY>=parentCell.top&&tY<=parentCell.bottom)
    {//if1
    var subTables=parentTable.cells[i].getElementsByTagName("table");
    if(subTables.length==0)// 如果鼠标所在的列中没有没有子表,直接增加子对象(table)
    {
    if(tX>=parentCell.left&&tX<=parentCell.right&&tY>=parentCell.top&&tY<=parentCell.bottom)
    {parentTable.cells[i].appendChild(ao);}
    break;
    }
    for(var j=0;j<subTables.length;j++)//列中存在子表的处理
    {
    var subTable=getInfo(subTables[j]);
    if(tX>=subTable.left&&tX<=subTable.right&&tY>=subTable.top&&tY<=subTable.bottom)
    {
    parentTable.cells[i].insertBefore(ao,subTables[j]);
    break;
    }else{
    parentTable.cells[i].appendChild(ao);
    }
    }
    }//if1
    }//for1
    }
    function dragEnd(){
    if(!draged)return;
    draged=false;
    //---save sub table position---
    var pttyle="";
    for(var i=0;i<parentTable.cells.length;i++){//for1
    var subTables=parentTable.cells[i].getElementsByTagName("table");if(subTables.length==0)
    {
    pttyle+="|";
    break;
    }else{
    for(var j=0;j<subTables.length;j++)//列中存在子表的处理
    {
    if(subTables[j].className!="dragTable") continue; //这里仅仅对className==dragTable的表处理,排除组织页面中使用的table
    pttyle+=subTables[j].id+","+subTables[j].rows[0].cells[0].innerText+":";
    }
    pttyle+="|";
    }
    }//for1
    setCookie("pttyle",pttyle,"");
    //---save sub table position end---
    mm=ff(150,15);//
    }
    function getInfo(o){//取得对象的绝对坐标
    var to=new Object();
    to.left=to.right=to.top=to.bottom=0;
    var twidth=o.offsetWidth;
    var theight=o.offsetHeight;
    while(o!=document.body){
    to.left+=o.offsetLeft;
    to.top+=o.offsetTop;
    o=o.offsetParent;
    }
    to.right=to.left+twidth;
    to.bottom=to.top+theight;
    return to;
    }
    function ff(aa,ab){//用于恢复位置,来自该死的GOOGLE网站;aa/ab其值越大恢复的速度越快
    var ac=parseInt(getInfo(tdiv).left);
    var ad=parseInt(getInfo(tdiv).top);
    var ae=(ac-getInfo(ao).left)/ab;
    var af=(ad-getInfo(ao).top)/ab;
    return setInterval(function(){if(ab<1){
    clearInterval(mm);
    tdiv.removeNode(true);
    ao=null;
    return
    }
    ab--;
    ac-=ae;
    ad-=af;
    tdiv.style.left=parseInt(ac)+"px";
    tdiv.style.top=parseInt(ad)+"px"
    }
    ,aa/ab)
    }
    function inint(){//初始化
    /*根据cookie组织父表*/
    var pttyle=getcookie("pttyle");if (pttyle.length>0){
    //*****获得父表中所有的子表对象***/
    var ctCount=0; //计数器
    var stObjects=new Array();//保存子表对象for(var i=0;i<parentTable.cells.length;i++){
    var subTables=parentTable.cells[i].getElementsByTagName("table");//获得子表
    for(var j=0;j<subTables.length;j++){
    stObjects[ctCount]=subTables[j];
    ctCount++;
    parentTable.cells[i].removeChild(subTables[j]); //删除列中的子表对象
    }
    }//读取cookie中子表对象id
    var tempCells=pttyle.split("|");//因为格式为 pttyle=stid,stt:stid,stt:|stid,stt:stid,stt:|//begin for2
    for(var i=0; i<tempCells.length-1;i++)//拆成数组时存在一个多余的元素,故循环减去1
    {
    var tempSTs=tempCells[i].split(":");
    for (var j=0;j<tempSTs.length-1;j++)//遍历子表信息,
    {
    for(var n=0;n<stObjects.length;n++)//从子表对象数组中查询子表对象
    {
    if(tempSTs[j].indexOf(stObjects[n].id)!=-1)//id 值存在
    {
    parentTable.cells[i].appendChild(stObjects[n]);break;
    }
    }
    }
    }//end for2
    }//pttyle.length>0 End/*根据cookie组织父表结束*//*设置拖拽的样式和事件*/
    for(var i=0;i<parentTable.cells.length;i++){
    var subTables=parentTable.cells[i].getElementsByTagName("table");//获得子表
    for(var j=0;j<subTables.length;j++){
    if(subTables[j].className!="dragTable") continue;
    subTables[j].rows[0].className="dragTR";//给行添加表示可以移动的样式
    subTables[j].rows[0].attachEvent("onmousedown",dragStart);// 将指定函数绑定到事件,以便每当该事件在对象上触发时都调用该函数
    subTables[j].attachEvent("ondrag",draging);// 将draging函数邦定到进行拖曳操作时,在源对象上持续触发的事件。
    subTables[j].attachEvent("ondragend",dragEnd);//ondragend 事件:当用户在拖曳操作结束后释放鼠标时在源对象上触发。
    }
    }
    /*设置拖拽的样式和事件结束*/
    }
    inint();
    </script>
    </body>
    </html>
    ------------------
    来源于网络
      

  2.   


    <title></title> 
    <script type="text/javascript"> 
    function Drag(o, e){ 
    var e = window.event || e; 
    var _x = e.offsetX || e.layerX; 
    var _y = e.offsetY || e.layerY; document.onmousemove = function(e){ 
    var e = window.event || e; 
    o.style.left = e.clientX - _x + 'px'; 
    o.style.top = e.clientY - _y + 'px'; 
    o.style.cursor="move"; 

    document.onmouseup = function(e){ 
    document.onmousemove = null; 
    o.style.filter = o.style.opacity = ''; 
    o.style.cursor="default"; 


    </script> 
     
    <body> 
    <div onmousedown="Drag(this, event)" style="position:absolute;border:1px solid red;background:pink;width:400px;height:300px;"></div> 
    </body> 精简的 能cookie保存位置
      

  3.   


    <!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>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>无标题文档</title>
    <script type="text/javascript">
    /***************************************/
    var cookieOperate = {
    cookieTemp: function() {
    return (document.cookie) ? document.cookie : null;
    },
    cookieJson: function() {
    var _cookie = this.cookieTemp();
    var _json = null;
    if(_cookie) {
    _json = {};
    var _div;
    var _list = _cookie.split(';');
    for(var i = 0; i < _list.length; i++) {
    _div = _list[i].indexOf('=');
    if(_div) {
    _json[decodeURI(_list[i].substr(0, _div))] = decodeURI(_list[i].substr(_div + 1));
    }
    }
    }
    // for(var a in _json){
    // alert(a == 'pos')
    // }
    return _json;
    },
    selectCookie: function(key) {
    var _json = this.cookieJson();
    if(_json) {
    return (_json[key]) ? _json[key] : null;
    }
    },
    addCookie: function(key, value, time) {
    var _value = encodeURI(key) + '=' + encodeURI(value);
    if(typeof(time) != 'undefined') {
    _value += ';expires=' + time;
    }
    document.cookie = _value;
    },
    delCookie: function(key) {
    this.addCookie(key, '');
    }
    }
    /**********************************************************/var $ = function(id) {
    return (typeof(id) == 'string') ? document.getElementById(id) : id;
    }
    var $Array = function(list) {
    var _array = [];
    for(var i = 0; i < list.length; i++) {
    _array.push(list[i]);
    }
    return _array;
    }
    var $Bind = function(method, handler, flag) {
    var _arg = $Array(arguments);
    _arg.splice(0,3);
    if(flag) {
    return function(ev) {
    return method.apply(handler, [(window.event || ev)].concat(_arg));
    }
    } else {
    return function() {
    return method.apply(handler, _arg);
    }
    }
    }
    var $EventPos = function(ev) {
    var _x = ev.pageX || (ev.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft));
    var _y = ev.pageY || (ev.clientY + (document.documentElement.scrollTop || document.body.scrollTop));
    return [_x, _y];
    }
    var $StopEvent = function(ev) {
    if(ev.stopPropagation) {
    ev.stopPropagation();
    ev.preventDefault();
    } else {
    ev.cancelBubble = true;
    ev.returnValue = false;
    }
    }
    var $AddEvent = function(element, type, fun) {
    if(element.addEventListener) {
    element.addEventListener(type, fun, false);
    } else if(element.attachEvent) {
    element.attachEvent('on' + type, fun);
    }
    }
    var $RemoveEvent = function(element, type, fun) {
    if(element.removeEventListener) {
    element.removeEventListener(type, fun, false);
    } else if(element.detachEvent) {
    element.detachEvent('on' + type, fun);
    }
    }
    /***********************************************************/
    var Move = function(op) {
    this.options = op;
    if(!this.options.list || this.options.list <= 0) {
    return;
    }
    this.listLen = this.options.list.length;
    this.pos = [];
    this.posOver = [false, false];
    this.posList = [];
    this.mouseMoveEvent;
    this.mouseUpEvent
    var _self = this;
    $AddEvent(this.options.list[0], 'mousedown', $Bind(this.ready, this, true));
    this.init();
    }
    Move.prototype = {
    init: function() {
    var _pos = cookieOperate.selectCookie(this.options.key);
    if(_pos) {
    _pos = _pos.split('|');
    for(var i = 0; i < this.listLen; i++) {
    this.pos.push(_pos[i].split(','));
    }
    this.setPos();
    }
    },
    ready: function() {
    var _pos = $EventPos(arguments[0]);
    var _element, _x, _y;
    this.posList = [];
    for(var i = 0; i < this.listLen; i++) {
    _x = parseInt(this.options.list[i].style.left);
    _y = parseInt(this.options.list[i].style.top);
    this.posList.push([_pos[0] - _x, _pos[1] - _y]);
    if(!this.pos[i]) {
    this.pos[i] = [_x, _y];
    }
    }
    this.mouseMoveEvent = $Bind(this.move, this, true);
    this.mouseUpEvent = $Bind(this.stop, this, false);
    $AddEvent(document, 'mousemove', this.mouseMoveEvent);
    $AddEvent(document, 'mouseup', this.mouseUpEvent);
    $StopEvent(arguments[0]);
    },
    stop: function() {
    this.posList = [];
    var _pos = this.updatePos();
    cookieOperate.addCookie(this.options.key, _pos);
    $RemoveEvent(document, 'mousemove', this.mouseMoveEvent);
    $RemoveEvent(document, 'mouseup', this.mouseUpEvent);
    },
    move: function() {
    var _pos = $EventPos(arguments[0]);
    var _x = _pos[0] - this.posList[0][0];
    var _y = _pos[1] - this.posList[0][1];
    if(this.options.size) {
    this.posOver[0] = (_x <= 0 || _x + this.options.list[0].offsetWidth >= this.options.size[0]) ? true : false;
    this.posOver[1] = (_y <= 0 || _y + this.options.list[0].offsetHeight >= this.options.size[1]) ? true : false;
    }
    for(var i = 0; i < this.listLen; i++) {
    if(!this.posOver[0]){
    this.pos[i][0] = _pos[0] - this.posList[i][0];
    this.options.list[i].style.left =  this.pos[i][0] + 'px';
    }
    if(!this.posOver[1]){
    this.pos[i][1] = _pos[1] - this.posList[i][1];
    this.options.list[i].style.top = this.pos[i][1] + 'px';
    }
    }
    $('p').value = this.pos;
    },
    setPos: function() {
    for(var i = 0; i < this.listLen; i++) {
    this.options.list[i].style.left =  this.pos[i][0] + 'px';
    this.options.list[i].style.top =  this.pos[i][1] + 'px';
    }
    },
    updatePos: function() {
    var _pos = [];
    for(var i = 0; i < this.listLen; i++) {
    _pos.push(this.pos[i].join(','));
    }
    return _pos.join('|');
    }
    }
    </script>
    </head>
    <body>
    <input type='text' id='p' />
    <div id='test' style='width:200px;height:100px;background:#f00;position:absolute;left:0px;top:0px;'></div>
    <script type="text/javascript">
    new Move({
    size: [900, 450],   //可移动范围(相对于己定义position的父级元素;不限制则为null)
    list: [$('test')], //要移动的元素(第一个元素为操作句柄)
    key: 'pos' //cookie的名称
    })
    </script>
    </body>
    </html>