在第一个div中添加一个类来样式内部div



我有一个动态生成的元素列表,除了第一个元素外,所有元素的样式都相同。如果第一个没有渲染,我希望第二个(现在是第一个)具有第一个的样式。

  <div class="container">
    <a><div>first</div></a>
    <a><div>second</div></a>
    <a><div>third</div></a>
    <a><div>fourth</div></a>
    </div>

我试着只用CSS来做这件事,但没有得到想要的结果。

.container a:first-child div{
background:red;
}

我还试图通过jquery向第一个div添加一个类,但它甚至没有添加我的类:

$('.container a:first div').addClass('aaaa');

既然这两种方法似乎都不起作用,我该如何完成我想要做的事情?主要是想修复我的CSS答案,但如果不可能的话,jquery也可以。


用例:

我正在构建一种时间表配置文件,但由于我们的框架不支持日历小部件,我们填写数据,然后使用Date.parse()/moment.js来获得时间戳。然后,我们将日期(即:2016年6月1日)与当前日期的时间戳进行比较。if current date > event-date,则事件日期不会呈现。

我们最多存储4个活动日期,我正在努力使其自我贬值,这样我们就不必每次活动完成时都更新它。


渲染HTML示例:

<div class="container events" style="margin-top: 28px;">
  <h3>Upcoming Meetups</h3>
  <div class="hugs-post-instructions">blah blah<br>Click on each button to be taken to the registration page.</div>
  <a href="#">
    <div class="square-button">Next Meetup: May 19, 2016
    </div>
  </a>
  <a href="#">
    <div class="square-button">Upcoming Meetup: September 22, 2016
    </div>
  </a>
  <a href="#">
    <div class="square-button">Upcoming Meetup: December 1, 2016
    </div>
  </a>
</div>

啊,根据您的更新,我相信您希望:nth-of-type伪类作为您的选择器:

.container a:nth-of-type(1) div {
  background: red;
}
<div class="container events" style="margin-top: 28px;">
  <h3>Upcoming Meetups</h3>
  <div class="hugs-post-instructions">blah blah
    <br>Click on each button to be taken to the registration page.</div>
  <a href="#">
    <div class="square-button">Next Meetup: May 19, 2016
    </div>
  </a>
  <a href="#">
    <div class="square-button">Upcoming Meetup: September 22, 2016
    </div>
  </a>
  <a href="#">
    <div class="square-button">Upcoming Meetup: December 1, 2016
    </div>
  </a>
</div>

:first-child伪类只选择父元素的第一个子元素,而不是特定类型的第一个子,这就是为什么它不适用于您的原因。

或者,您可以突出显示第一个div,方法是给它们所有一个红色背景,然后为所有相邻的同级删除它:

.container a div {
    background:red;
}
.container a + a div {
    background:inherit;
}
<div class="container events" style="margin-top: 28px;">
  <h3>Upcoming Meetups</h3>
  <div class="hugs-post-instructions">blah blah<br>Click on each button to be taken to the registration page.</div>
  <a href="#">
    <div class="square-button">Next Meetup: May 19, 2016
    </div>
  </a>
  <a href="#">
    <div class="square-button">Upcoming Meetup: September 22, 2016
    </div>
  </a>
  <a href="#">
    <div class="square-button">Upcoming Meetup: December 1, 2016
    </div>
  </a>
</div>

最新更新