用一个简单的函数重新排列元素

Rearranging elements with a simple function

本文关键字:新排列 排列 元素 函数 简单 一个      更新时间:2023-09-26
 function rearrange(x, y) {
    x.parentNode.replaceChild(x, y);
    x.parentNode.insertBefore(y,x); 
 }

如果我这样做

var a = document.getElementsByClassName('btn-button-google')[0];
var b = document.getElementsByClassName('btn-button-doodle')[0];
rearrange(b,a);

我得到以下错误

NotFoundError: Failed to execute 'replaceChild' on 'Node': The node to be replaced is not a child of this node.

我理解,因为a是在一个htmldiv和b是在另一个div,但我很好奇如何解决这个问题。这是

rearrange(b.parentNode,a.parentNode);

因为它们在同一个节点。

HTML例子

<div class="container">
   <div class="group">
     <a href="" class="btn-button-bold"><a>
     <a href="" class="btn-button-italic"><a>
     <a href="" class="btn-button-strike"><a>
   </div>
   <div class="group">
     <a href="" class="btn-button-font"><a>
     <a href="" class="btn-button-ffamily"><a>
     <a href="" class="btn-button-google"><a>
   </div>
   <div class="group">
      <a href="" class="btn-button-smilies"><a>
     <a href="" class="btn-button-doodle"><a>
     <a href="" class="btn-button-source"><a>
   </div>
</div>

.replaceChild方法接受替换作为第一个参数,将要替换的子元素作为第二个参数。你把它们颠倒了,这就导致了错误。

此外,如果目的是交换,则需要保留对y原始位置的引用,因为一旦移动它,它将被遗忘。

这将在大多数情况下工作:

var yPar = y.parentNode, ySib = y.nextSibling; 
x.parentNode.replaceChild(y, x); 
yPar.insertBefore(x, ySib);

请记住,还有一个问题需要考虑。只要两个节点有不同的父节点,这就不是问题,但是如果它们共享父节点,并且彼此相邻,并且缓存的nextSiblingx相同,那么它就没有影响。因此,如果可能的话,您需要对此进行测试,并处理这种特殊情况。