假设在下面的HTML中,类为ChildBar的元素可以是,也可以不是.

<div class="Parent">
    <div class="ChildFoo"></div>
    <div class="ChildBar"></div> <!-- Could not be -->
    <div class="ChildBaz"></div>
</div>

此外,假设ChildBaz必须在4px年前从ChildFoo退休,但必须在6px年前从ChildBar退休.在css中,它将是:

.ChildFoo + .ChildBaz {
  margin-top: 4px;
}

.ChildBar + .ChildBaz {
  margin-top: 6px;
}

现在,我想通过JavaScript将元素ChildBar安装到正确的位置,如下所示:

  1. 围绕ChildBar的标记的更改不能阻止JavaScript的行为.这意味着不能使用像Element.after()引用sibling 元素这样的方法.
  2. 我需要mounting,而不是从隐藏状态显示.
  3. 以上款式绝对不能打破.

在以下加价的情况下,replaceWith解决方案将很容易.

<div class="Parent">
    <div class="ChildFoo"></div>
    <div id="ChildBarMountingPoint"></div>
    <div class="ChildBaz"></div>
</div>

Hoewever,ID为ChildBarMountingPoint的元素会阻止样式.是否有一些magic元素被CSS忽略,因此.ChildFoo + ChildBaz被正确应用?(如果没有,则包含replaceWith的解决方案分支是死胡同,我必须找到其他解决方案分支).

推荐答案

有没有一个"魔力"元素不存在于css Select 器中--没有.但是有only个元素由 Select 器匹配,还有其他 node 类型.也许你可以用其中的一个.

例如,一种可能性是使用注释.假设您知道这两个/三个元素将位于类为.Parent的已知父元素中,您可以这样做:

document.querySelector('#addChildBar').addEventListener('click', () => {
  
  Array.from(document.querySelector('.Parent').childNodes).find(n => {
    return n.nodeType === 8 && n.data === ' ChildBarMountingPoint '
  }).replaceWith(Object.assign(document.createElement('div'), {
    className: 'ChildBar' 
  }));
  
})
.ChildFoo + .ChildBaz {
  margin-top: 4px;
  color: red;
}

.ChildBar + .ChildBaz {
  margin-top: 6px;
  color: green;
}
<div class="Parent"> 
    <div class="ChildFoo">foo</div>
    <!-- ChildBarMountingPoint -->
    <div class="ChildBaz">baz</div>
</div>
<hr>
<button type="button" id="addChildBar">Add ChildBar</button>

注释 node 是 node 类型8.

如果您不知道父 node ,则需要逐个 node 遍历DOM以找到正确的注释 node .

Javascript相关问答推荐

类型脚本中只有字符串或数字键而不是符号键的对象

如何修复(或忽略)HTML模板中的TypeScript错误?'

有没有可能使滑动img动画以更快的速度连续?

我的服务工作器没有连接到我的Chrome扩展中的内容脚本.我该怎么解决这个问题?

构造HTML表单以使用表单数据创建对象数组

在我的index.html页面上找不到我的Java脚本条形图

如何在DYGRAPS中更改鼠标事件和键盘输入

如何在HTMX提示符中设置默认值?

使用自动识别发出信号(&Q)

FireBase FiRestore安全规则-嵌套对象的MapDiff

本地损坏的Java脚本

我们是否可以在reactjs中创建多个同名的路由

更新文本区域行号

如何阻止外部脚本进入顶层导航

在执行console.log(new X())时记录一个字符串

使用jQuery每隔几秒钟突出显示列表中的不同单词

递归地将JSON对象的内容上移一级

如何让noWrap在嵌套在Alert/AlertTitle组件中的排版组件中工作?

我在JS代码中收到超过最大调用堆栈大小的错误,但我找不到原因.有谁能帮我搬一下吗?

JAVASCRIPT|导入模块中断FOR循环