交换 3 divs 并使选择 div 到中心

Swap 3 divs and make the selection div go to the center

我有三个 div,我希望每次单击任何 div 时,它都会与第二个 div 交换,这意味着在中心.

我这样试过,但没用:

function swapDiv(event, elem) {
  elem.parentNode.insertBefore(elem, elem.parentNode.secondChild);
}
<div class="all-div-container">
  <div class="div1" onclick="swapDiv(event,this);">
    1
  </div>
  <div class="div2" onclick="swapDiv(event,this);">
    2
  </div>
  <div class="div3" onclick="swapDiv(event,this);">
    3
  </div>
</div>

1 2 3 当我点击 3 结果必须是 1 3 2根据这个结果,我点击 1 它必须是 3 1 2

function swapDiv(event, elem) {
    // get all elements in .all-div-container
    const allElements = [...elem.parentElement.children];
    // get index of target elem
    const targetIndex = allElements.indexOf(elem);
    // get center element
    const centerElem = allElements[1];
    // exit from function if we clicked at center elem
    if (elem === centerElem) return;
    // move center element
    if (targetIndex === 0) {
        elem.parentElement.prepend(centerElem)
    } else {
        elem.parentElement.append(centerElem)
    }
}
<div class="all-div-container">
    <div class="div1" onclick="swapDiv(event,this);">
        1
    </div>
    <div class="div2" onclick="swapDiv(event,this);">
        2
    </div>
    <div class="div3" onclick="swapDiv(event,this);">
        3
    </div>
</div>

考虑以下因素。

$(function() {
  $(".all-div-container > div").click(function(event) {
    if ($(this).index() == 0) {
      return false;
    }
    var $prev = $(this).prev();
    var $self = $(this).detach();
    $prev.before($self);
  });
});
.all-div-container>div {
  height: 2em;
  width: 100%;
  border: 1px solid #ccc;
  border-radius: 3px;
  margin-bottom: 3px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="all-div-container">
  <div class="div1">1</div>
  <div class="div2">2</div>
  <div class="div3">3</div>
</div>

您没有说明如果单击第一项会发生什么。此代码将交换单击的元素和上一个元素。