如何在属性选择器中使用/模拟类似正则表达式的反向引用?

2022-01-10 00:00:00 css-selectors css

我想要做的是在一个地方编写一个匹配任意值的选择器,然后需要一个不同的值等于它.如果 [attr="value"] 将value"解析为正则表达式,那么这将解决我的问题:

What I want to do is write a selector that matches an arbitrary value in one place, then later requires a different value be equal to it. If [attr="value"] parsed "value" as a regex, then this would solve my problem:

*[class="(.+)"] *[class="if_1"] {/* styles */}

显然我可以单独列出每个可能的类,但这会带来很大的便利.

Obviously I could just list each possible class individually, but that takes a great deal of convenience out of it.

这可能吗?

推荐答案

不,不可能.属性选择器几乎是完全静态的,几乎不提供动态匹配功能(除了子字符串匹配,它仍然是静态的,不是基于动态模式的).它们不支持您在日常正则表达式中看到的任何内容.

No, it's not possible. Attribute selectors are almost completely static and provide almost no dynamic matching functionality (beyond that of substring matches, which are still static and not dynamic pattern-based). They do not support anything like what you see in everyday regular expressions.

诸如 Sass 或 LESS 之类的样式表预处理器将允许您生成所需的静态 CSS 规则,但所做的只是自动执行手动任务,即分别列出所有可能的值,这证明了我的第一点.

A stylesheet preprocessor such as Sass or LESS will allow you to generate the static CSS rules needed, but all that does is automate the manual task of listing all possible values individually, which proves my first point.

相关文章