如何在另一个div元素中移动div元素?

时间:2015-08-07 18:23:50

标签: javascript jquery html css

var $selected = $();
  var $itemLv1 = $("#create-summary .lv1"); 
  $itemLv1.click(function(){
      $selected = $(this);
      $(this).toggleClass('clicked').siblings().removeClass('clicked');
  });

  $("#moveUp").click(function(){
      $selected.add($selected.nextUntil(":not(.lv2)"))        
              .insertBefore($selected.prevAll(".lv1:first"));
  });

  $("#moveDown").click(function(){
    $selected.add($selected.nextUntil(":not(.lv2"))
             .insertAfter($selected.nextAll(".lv1:first"));
  });
.clicked{
  color: red;
  font-weight:700;
}

.lv2, .lv3 {
  margin-left:15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="create-summary">
            <div class="lv1"> Introduction</div>
            <div class="lv1">1. AAA</div>
            <div class="lv1">2. BBB</div>
            <div class="lv1">3. CCC
              <div class="lv2">3.1 aaa</div>
              <div class="lv2">3.2 bbb</div>
              <div class="lv2">3.3 ccc</div>
              <div class="lv2">3.4 ddd
                <div class="lv3">3.4.1 xxxxx</div>
                <div class="lv3">3.4.2 yyyyy</div>
                <div class="lv3">3.4.3 zzzzz</div>
              </div>
            </div>
            <div class="lv1">4. DDD</div>
            <div class="lv1">5. EEE</div>
        </div>

<button type="button" id="moveUp">Up </button> / 
<button type="button" id="moveDown">Down</button>

现在,我可以使用其子元素向上或向下移动lv1元素。

但是,如何只在子div中移动div元素?(仅限lv3或lv4甚至lv5或lv6)

Fir示例,我想仅在lv2中移动“ccc”或仅在lv3中移动xxxxx。 有什么方法可以做到吗?

1 个答案:

答案 0 :(得分:1)

我认为您需要这样的功能,

var $selected = $();
var $itemLv1 = $("#create-summary [class^=lv]");

$itemLv1.click(function (e) {
    $selected = $(this);
    var x = $(this).toggleClass('clicked');
    $("[class^=lv]").not(x).removeClass("clicked child").addClass("child");
    x.siblings().removeClass('clicked');
    e.stopPropagation();
});

$("#moveUp").click(function () {
    $selected.insertBefore($selected.prev("[class^=lv]"));
});

$("#moveDown").click(function () {
    $selected.insertAfter($selected.next("[class^=lv]"));
});

DEMO