【问题标题】:Add div after every third post每三篇文章后添加 div
【发布时间】:2015-05-20 18:20:02
【问题描述】:

我发现这篇文章符合我的要求: Append Span Tag, after every 3rd div Jquery http://jsfiddle.net/pxaS4/2/

但我使用的是三列布局。我想澄清一下:每三个帖子之后,如果它们的高度不同,它们将始终保持 3 连续。

html:

<div class="post-listing">

    <div class="post-item">
    This text make the post-item different height.
    </div>

    <div class="post-item">
    This text make the post-item different height. This text make the post-item different height.
    </div>

    <div class="post-item">
    This text make the post-item different height. 
    </div>

    <div class="post-item">
    This text make the post-item different height. This text make the post-item different height. This text make the post-item different height.
    </div>

    <div class="post-item">
    This text make the post-item different height.
    </div>

    <div class="post-item">
    This text make the post-item different height. This text make the post-item different height.
    </div>

    <div class="post-item">
    This text make the post-item different height. This text make the post-item different height. This text make the post-item different height.
    </div>

    <div class="post-item">
    This text make the post-item different height.
    </div>

    <div class="post-item">
    This text make the post-item different height.
    </div>

</div>

CSS:

.clear {
  clear: both;
  color: #000;
}

.post-listing {
  width: 300px;
}

.post-listing .post-item {
  float: left;
  color: red;
  background: #ccc;
  width: 32%;
  margin-right: 2%;
  margin-bottom: 30px;
}

.post-listing :nth-child(3n+0).post-item {
  margin-right: 0%;
  clear: right;
}

这似乎工作正常。问题是当我尝试在每三个帖子之后使用 jquery 添加一个 div 类“clear”时。这是我所拥有的,但它不起作用:

$('div.post-listing > div.post-item:nth-child(3n)').after('<div class="clear">this is the clear class</div>');

jsfiddle(非工作)在这里:jsfiddle

非常感谢任何帮助。 谢谢

【问题讨论】:

标签: jquery html css


【解决方案1】:

您无需添加新的divs。将clear: left 添加到3n+1 .post-item

.post-item:nth-child(3n+1) {clear: left;}

https://jsfiddle.net/936qtbu5/1/

【讨论】:

  • 这比我尝试做的要容易得多...谢谢!
【解决方案2】:

首先,您的 jQuery 不工作的原因是 jQuery 没有被加载到您的小提琴中。如果您加载最新的 jQuery 框架,您的 jQuery 代码可以正常工作。

其次,您想要做的事情可以在 CSS 中完成。

您可以像这样定位每个第 3 个项目并删除其右边距:

.post-listing .post-item:nth-child(3n) {
    margin-right: 0;
}

您还可以像这样清除每个新行的第一项:

.post-listing .post-item:nth-child(3n+1) {
    clear: both;
}

由于每行有三个项目,我们输入3n。 这意味着无论您有多少行,您将始终定位正确数量的项目。 +1 将在上一行的最后一项之后抓取 next .post-listing 项。

例如,假设您有两行,每行有 3 个项目。 使用 nth-child(3n+1) 将选择项目编号 1 和 4。

n 的第一次迭代为 0。 (3 * 0) + 1 = 1

n 的第二次迭代为 1。 (3 * 1) + 1 = 4

以下是仅使用 CSS 的更新小提琴的链接: https://jsfiddle.net/936qtbu5/4/

【讨论】: