Html 如何让 CSS 选择以字符串开头的 ID(不是在 Javascript 中)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11496645/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get CSS to select ID that begins with a string (not in Javascript)?
提问by guptron
If the HTML has elements like this:
如果 HTML 有这样的元素:
id="product42"
id="product43"
...
How do I match all of those id's starting with "product"?
如何匹配所有以“产品”开头的 ID?
I've seen answers that do this exactly using javascript, but how to do it with only CSS?
我已经看到完全使用 javascript 做到这一点的答案,但是如何仅使用 CSS 来做到这一点?
回答by Niet the Dark Absol
[id^=product]
^=
indicates "starts with". Conversely, $=
indicates "ends with".
^=
表示“开始于”。反之,$=
表示“以”结尾。
The symbols are actually borrowed from Regex syntax, where ^
and $
mean "start of string" and "end of string" respectively.
这些符号实际上是从 Regex 语法借来的,其中^
和 分别$
表示“字符串开头”和“字符串结尾”。
See the specsfor full information.
有关完整信息,请参阅规格。
回答by Blender
I'd do it like this:
我会这样做:
[id^="product"] {
...
}
Ideally, use a class. This is what classes are for:
理想情况下,使用类。这就是类的用途:
<div id="product176" class="product"></div>
<div id="product177" class="product"></div>
<div id="product178" class="product"></div>
And now the selector becomes:
现在选择器变成了:
.product {
...
}
回答by Musa
回答by Luigi Spezia
I noticed that there is another CSS selector that does the same thing . The syntax is as follows :
我注意到还有另一个 CSS 选择器可以做同样的事情。语法如下:
[id|="name_id"]
This will select all elements ID which begins with the word enclosed in double quotes.
这将选择以双引号括起来的单词开头的所有元素 ID。