javascript - 我如何告诉 CSS 重新计算 :first-of-type after DOM dynamically changes?

标签 javascript html css

我有以下 CSS 规则:

        .block:first-of-type{
            border-top: 1px solid black;
        }

        .block:last-of-type{
            border-bottom: 1px solid black;
        }

这个 .block div 是通过 AJAX 生成的,可以多次添加到页面中。问题是每次我添加其中一个时,所有 div 都被读取为文档的第一个和最后一个。我认为这是因为 CSS 无法识别 DOM 中发生的更改。我该如何解决这个问题?

最佳答案

all divs are read as both first and last of the document

你误解了 :first-of-type:last-of-type 的意思。

参见 the spec

Same as :nth-of-type(1). The :first-of-type pseudo-class represents an element that is the first sibling of its type in the list of children of its parent element.

重要的一点是其父元素的子元素 不是 文档

你可以在这里看到它做得非常正确:

function middle() {
  var d = document.createElement("div");
  d.appendChild(document.createTextNode("inserted in middle"));
  var p = document.querySelector("div + div + div");
  p.parentNode.insertBefore(d, p);
}

function first() {
  var d = document.createElement("div");
  d.appendChild(document.createTextNode("inserted at top"));
  var p = document.querySelector("div");
  p.parentNode.insertBefore(d, p);
}

setTimeout(middle, 2000);
setTimeout(first, 4000);
div:first-of-type {
  border-top: 1px solid black;
}
div:last-of-type {
  border-bottom: 1px solid black;
}
<div>Original First</div>
<div>Original Second</div>
<div>Original Third</div>
<div>Original Fourth</div>
<div>Original Fifth</div>

您大概正在创建一个结构,例如:

<div>
    <div class="block"></div>
</div>
<div>
    <div class="block"></div>
</div>
<div>
    <div class="block"></div>
</div>

…其中该类的每个 div 都是其父元素中的第一个 div。

鉴于该布局,您将需要更类似于 :first-of-type > .block 的东西作为您的选择器。

您需要的选择器的确切性质取决于您正在创建的 DOM,但您尚未与我们分享。

关于javascript - 我如何告诉 CSS 重新计算 :first-of-type after DOM dynamically changes?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33593266/

相关文章:

javascript - 在 javascript 中将多值 Map<String, Object [ ]> 转换为 json

javascript - 为什么我不能将 Backbone.Collection 用作通用集合?是否有执行此操作的实现?

javascript//这里发生了什么?

javascript - 如何在客户端读取excel文件内容?

html - 为什么我的@media 查询在特定行之后没有被代码编辑器注册?

css - 将 `<fieldset>` 的宽度设置为最大包含元素的宽度

html - 在图像的底部开始内容容器

jquery - 为什么文字大小没有增加?

html - 我如何点击表中的第二个链接,这些值在 Selenium RC 服务器中动态变化

php - 如何在 HTML 中显示 SQL TABLE 单击下拉列表