我的回答很笼统,从未与问题直接相关,因为这已经很老了,到目前为止,此页面上的其他答案已经解决了。
这个答案的第一部分是枯燥的理论,有助于理解选项。
第二部分是该理论的应用实例。
1) 属性选择器
Substring matching attribute selectors:
[att^=val]
表示具有 att 属性的元素,其值以前缀“val”开头。如果 "val" 是空字符串,则选择器不代表任何内容。
[att$=val]
表示具有 att 属性的元素,其值以后缀“val”结尾。如果 "val" 是空字符串,则选择器不代表任何内容。
[att*=val]
表示具有 att 属性的元素,其值包含至少一个子字符串“val”的实例。如果 "val" 是空字符串,则选择器不代表任何内容。
另外还有更多的选择器,在规范中它们在Attribute presence and value selectors一章中排序:
[att]
表示具有 att 属性的元素,无论该属性的值如何。
[att=val]
表示具有 att 属性的元素,其值正好是“val”。
[att~=val]
表示具有 att 属性的元素,其值为以空格分隔的单词列表,其中一个恰好是“val”。如果“val”包含空格,它永远不会代表任何东西(因为单词是用空格分隔的)。此外,如果“val”是空字符串,它永远不会代表任何东西。
[att|=val]
表示具有 att 属性的元素,其值要么正好是“val”,要么以“val”开头,紧跟“-”(U+002D)。
2) 如何根据事件在页面上选择多个内容的示例
当一个事件被触发时,通配符特别有用,比如一个带有特殊标签的页面被访问。相反,对于一个完全静态的页面,它们也很有用,但仍然可以注意到不同,即使它会是更多的 CSS 代码。
假设访问了带有标签action 的页面,那么 URL 将如下所示:
https://example.com/index.html#action
虽然只有一个 id 像这样被触发,但我们可以使用它来记录 CSS 中的一整套相关操作,但我们只需要将整个区域包含在 ID 为 action 的元素中即可:
/* all div-elements which are direct child of element with class `wrapper` are hidden: */
.wrapper>div {
display: none;
}
/* following line addresses all elements inside element with the id "action"
where the id is starting with "action_". This is only triggered when the
URL with hashtag "action" is called, because of usage of ":target":
*/
#action:target [id^="action_"] {
display: block;
}
/* following line addresses all elements inside element with the id "amother-action"
where the class is "another-action". This is only triggered when the
URL with hashtag "another-action" is called, because of usage of ":target".
This example shows that we never need ids but can use classes too:
*/
#another-action:target .another-action {
display: block;
}
<div id="action">
<div id="another-action">
<div class="wrapper">
<!-- this small menu is always shown as it's an unordered list and no div: -->
<ul>
<li><a href="#">No Action / Reset</a></li>
<li><a href="#action">Action</a></li>
<li><a href="#another-action">Another Action</a></li>
</ul>
<!-- The following div-elements are by default hidden and
only shown when some event is triggered: -->
<div id="action_1" class="another-action">
<!-- this is on both actions shown as the div has an id starting
with "action" and also a class "another-action" -->
Hello
</div>
<div id="action_2">
<!-- this is above only triggered by the CSS-rule
#action:target [id^="action_"] -->
World!
</div>
<div class="another-action">
<!-- This is above only triggered by the CSS-rule
#another-action:target .another-action -->
Everybody!
</div>
</div>
</div>
</div>
不同的结果如下:
- 当页面被调用时没有任何哈希,只显示菜单:
- 使用哈希
action调用页面时,可以看到下面的菜单:
你好
世界!
- 当使用哈希
another-action 调用页面时,可以在菜单下方看到以下内容:
你好
大家!
这样,我们可以混合很多内容,其中每个部分仅在特殊情况下显示。
仅当具有 id 的元素用内容和可选择的属性包围元素时,混合多个 id 和类才有效。在我上面的示例中,您可以看到 HTML 中的所有内容都写在 <div id="action"><div id="another-action"> 和 </div></div> 之间,就像这样,每个使用的事件都可以选择性地触发内容中的所有内容。
当然,CSS 也可以将此方法用于其他效果。隐藏或显示元素只是一个简单的示例,但您可以更改颜色、启动 CSS 动画以及通过 CSS 执行许多其他操作。
请注意不要在任何这些元素中发布任何机密内容,因为这种 CSS 解决方案没有安全性,仅用于区分视觉显示的情况。
您像这样隐藏或显示的任何内容在 HTML 源代码中始终可见。