如何在DOM树中保存/恢复对象的位置? [英] How do I save/restore an object's location in the DOM tree?

查看:96
本文介绍了如何在DOM树中保存/恢复对象的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下html:

 < ul> 
< li> test< / li>
< li class ='draggable'> special< / li>
< li> test< / li>
< / ul>

如何保存 .draggable 当前的DOM位置(一般地)?



我计划通过将 .draggable 附加到 document.body 并使的位置:absolute; 但是如果用户没有做任何事情,我需要恢复



我可以使用克隆,隐藏原件,并使用代理拖动,但我觉得这个问题可能已经更直接地解决了。 p>

想法?

解决方案

要保存对象的位置,您只需保存DOM之前引用了兄弟姐妹。如果没有兄弟姐妹,则保存父母。

 函数saveLocation(element){
var loc = {};

var item = $(element).prev();
loc.element = element;
if(item.length){
loc.prev = item [0];
} else {
loc.parent = $(element).parent()[0];
}
return(loc);
}

然后,恢复:

  function restoreLocation(loc){
if(loc.parent){
$(loc.parent).prepend(loc.element);
} else {
$(loc.prev).after(loc.element);
}
}


If I have the following html:

<ul>
  <li>test</li>
  <li class='draggable'>special</li>
  <li>test</li>
</ul>

How do I save .draggable's current DOM location (generically)?

I plan on dragging this .draggable around by by appending it to document.body and making the position: absolute; but I'll need to restore it if the user fails to do anything with it.

I could do this with clones, hiding the original, and using a proxy for dragging, but I feel like this problem has probably been solved more directly.

Thoughts?

解决方案

To save an object's position, you can just save the DOM reference to the sibling before it. If there is no sibling before it, then save the parent.

function saveLocation(element) {
    var loc = {};

    var item = $(element).prev();
    loc.element = element;
    if (item.length) {
        loc.prev = item[0];
    } else {
        loc.parent = $(element).parent()[0];
    }
    return(loc);
}

Then, to restore:

function restoreLocation(loc) {
    if (loc.parent) {
        $(loc.parent).prepend(loc.element);
    } else {
        $(loc.prev).after(loc.element);
    }
}

这篇关于如何在DOM树中保存/恢复对象的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆