jquery - 根据 div 中的元素数使用 css 设置 css 属性

标签 jquery html css

是否可以使用 CSS3 仅使用 CSS 格式化父 div 的子 div,例如:

  1. 当有 3 个 div 时,在 div 1 和 2 上设置属性 x。
  2. 当有 2 个 div 时,在 div 1 上设置属性 x
  3. 当有 1 个 div 时,在 div 1 上不设置属性 x

或者我必须为这个动态逻辑使用 jquery 吗?

最佳答案

.parent div {
  height: 1em;
  width: 1em;
  background: red;
  margin: 0.5em;
}
.parent div:last-child {
  background: green;
}
<div class="parent">
  <div></div>
  <div></div>
  <div></div>
</div>
<hr />
<div class="parent">
  <div></div>
  <div></div>
</div>
<hr />
<div class="parent">
  <div></div>
</div>

我认为你可以用纯 css 解决你的问题。

想想最后一个 child 选择器:http://www.w3schools.com/cssref/sel_last-child.asp

为所有 child 设置相同的样式,但对最后一个 child 应用不同的样式。

所以在 3 div 的情况下,第三个 div 将获得 last-child 样式 在 2 div 的情况下,第二个 child 将获得 last-child 样式等。

关于jquery - 根据 div 中的元素数使用 css 设置 css 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28294756/

相关文章:

javascript - jquery 中的 .find().html() 在 iframe 中使用时始终返回 null

javascript - JQuery 将输入掩码应用于字段 onfocus 并删除 onblur 以避免占位符文本出现问题

css - 如何排序和组合此 css 规则,以免重复太多?

css - PrimeFaces 大型菜单隐藏在中心内容、左侧和右侧栏后面

javascript - 动画 Accordion : how to make it work with variable height

html - css background-size 失败以及图像位置

jquery - Dojo 附加按钮(如 jQuery)

jquery - 如何在焦点输入的同一父级中滑动类

html - 使用 CSS 选择特定元素

html - Phonegap 和 Trigger.io 的比较