交换2 div元素Javascript

时间:2015-07-08 15:34:34

标签: javascript html asp.net

所以我想交换两个内部有CKEditor的div元素。我查看了之前的一些问题并试图这样做。一切都好,元素被交换了。但其中一个元素失去了内容,变得不可编辑。

<div id="sections">    
    <div id="apresentacao_div">
            <label id="apresentacao_label" for="apresentacao">Apresentação</label>
            <button class="btn btn-default">
                <span class="glyphicon glyphicon-remove"></span>
            </button>
            <button class="btn btn-default">
                <span class="glyphicon glyphicon-arrow-up"></span>
            </button>
            <CKEditor:CKEditorControl ID="apresentacao"></CKEditor:CKEditorControl>
    </div>
    <div id="intro_div">
            <label id="intro_label" for="intro">Introdução</label>
            <button class="btn btn-default" onclick="remove(this)">
                <span class="glyphicon glyphicon-remove"></span>
            </button>
            <button class="btn btn-default" onclick="upDiv(this)">
                <span class="glyphicon glyphicon-arrow-up"></span>
            </button>
            <CKEditor:CKEditorControl ID="intro"></CKEditor:CKEditorControl>
    </div>
</div>

我想用div =&#34;部分&#34;交换div中的两个div。这是我的交换代码:

function upDiv(ex) {
  var div = document.getElementById("sections").getElementsByTagName("div");
  for (i = 0; i < div.length; i = i + 4) {
    if (div[i + 4].id.localeCompare(ex.parentNode.id) == 0) {
      swapElements(div[i + 4], div[i]);
      return false;
    }
  }
  return false;
}

function swapElements(obj1, obj2) {
  obj2.nextSibling === obj1 ? obj1.parentNode.insertBefore(obj2, obj1.nextSibling) : obj1.parentNode.insertBefore(obj2, obj1);
}

for循环增加4,因为textarea转换为CKEditor会增加许多新的div(在这种情况下为4)。 有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

Not having too much familiarity with exactly what you are doing but i would try using a 'clone' method and then removing the original element off the page. It may be the values are not being copied, only the outline is but a clone should mean it duplicates as it is on the page and not how it is from the page source.

答案 1 :(得分:0)

只是交换数据呢?移动DOM元素也给我带来了问题,但这有效:

将upDiv替换为:

function upDiv()
{
    var introData = CKEDITOR.instances['intro'].getData();
    var presentacaoData = CKEDITOR.instances['apresentacao'].getData();
    CKEDITOR.instances['intro'].setData(presentacaoData);
    CKEDITOR.instances['apresentacao'].setData(introData);
    return false;
}

这将从一个获取数据,并将其放在另一个中,反之亦然。

另外,我注意到您的控件没有设置runat服务器属性。您可能想要更改此内容:

<CKEditor:CKEditorControl runat="server" ID="intro"></CKEditor:CKEditorControl>

最后,你可以按下按钮调用该功能:

<button class="btn btn-default" onclick="return upDiv();">
    <span class="glyphicon glyphicon-arrow-up"></span>
</button>