【问题标题】:CSS selector to match class with number greater thanCSS选择器匹配数字大于的类
【发布时间】:2014-10-02 17:11:24
【问题描述】:

我有一个使用 Sencha Touch 2 开发的移动混合应用程序,需要根据它运行的 iOS 版本进行一些自定义。

我曾经在我的 Sass 样式表中有以下选择器:

.x-ios-7 {
/* put here iOS7 customizations */

}

现在在 iOS8 中,框架添加了一个 x-ios-8 类而不是 x-ios-7,并且自定义显然被破坏了。

有没有办法选择x-ios-{i} 其中{i} >= 7 的所有类?

[编辑]

允许使用 Sass。 我不想硬编码已知案例。

【问题讨论】:

标签: css sass


【解决方案1】:

SASS

@for $i from 3 through 6 {
    .x-ios-#{$i} { background:blue; }
}

生成

.x-ios-3 { background:blue; }
.x-ios-4 { background:blue; }
.x-ios-5 { background:blue; }
.x-ios-6 { background:blue; }

常规 CSS

div { width:100px;height:100px;border:1px solid black;float:left; }
[class^="x-ios-"]:not([class*="1"]):not([class*="2"]) { background:blue; }

<div class="x-ios-1"></div>
<div class="x-ios-2"></div>
<div class="x-ios-3"></div>
<div class="x-ios-4"></div>
<div class="x-ios-5"></div>
<div class="x-ios-6"></div>


或者为您的用例想出第 n 个配方..

:nth-child(n+5) matches children 5, 6, 7, ...
:nth-child(2n+5) matches children 5, 7, 9, ...
:nth-child(-n+7) matches children 1, 2, 3, 4, 5, 6, 7
:nth-child(-3n+8) matches children 2, 5, and 8

【讨论】:

  • :nth-child() 在我的用例中不是一个选项。我将对要排除的情况进行硬编码,这是我能做的最好的事情。 Sass for 循环不是一个选项,因为我不想为未知的未来版本生成类。
  • 我会将:not([class*="1"]):not([class*="2"]) 更改为$= 否则它将匹配例如x-ios-10。但我仍然会遇到x-ios-11 的问题。我开始认为除了硬编码之外没有其他解决方案。
  • 对于那些有同样问题的人,这是我想出的解决方案:body[class*="x-ios-"]:not(.x-ios-6)。部署目标设置为 6.0,所以我不必担心以前的版本。
【解决方案2】:

在 vanilla CSS 中,您可以使用带有通配符的属性选择器来匹配任何以“x-ios-”开头的类名:

[class*='x-ios-'] {
  /* all ios */
}

然后对需要额外内容的已知案例进行硬编码:

.x-ios-7 {
  /* ios 7 */
}

编辑:正如文档的回答所暗示的,您可以像这样定位 >= ios7 (fiddle):

[class*='x-ios-']:not(.x-ios-3):not(.x-ios-4):not(.x-ios-5):not(.x-ios-6) {
   /* ios >= 7 */
}

【讨论】:

  • 重点是我不想硬编码已知案例:)
猜你喜欢
  • 2021-02-10
  • 1970-01-01
  • 1970-01-01
  • 2016-03-23
  • 1970-01-01
  • 1970-01-01
  • 2011-07-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多