html - 匹配包含部分 URL 和特定类的链接

标签 html css css-selectors

此页面上有一个带有不同链接的网页。我的目标是找到包含以下内容的链接:/dir/flowers/ 并具有类:flower big

并为它们设置不同的样式(即,将这些链接设为红色)。

以下是应该匹配的示例链接:

<a class="flower big" href="http://example.net/dir/flowers/spring.php">Spring</a> 
<a class="flower big" href="http://example.net/dir/flowers/winter.php">Winter</a>    
<a class="flower big" href="http://example.net/dir/flowers/fall.php">Fall</a>

等等

因此,如果链接包含:/dir/flowers/{*} 并且 具有类:"flower big" 那么它应该是匹配。

我尝试了类似下面的方法,但它不起作用:

(a[class="flower big"] AND a[href~="/dir/flowers/"] ) {color:red} 

最佳答案

您可以使用 2 CSS attribute selectors

  1. [class^="flower big"]^ 将查找属性名称为 class 且其第一个值以前缀为“花大”。

  2. [href*="/dir/flowers/"]* 将查找任何具有属性的 a href 的名称,其值至少包含一次字符串“/dir/flowers”作为子字符串。


a {
  display: block
}
[class^="flower big"][href*="/dir/flowers/"] {
  color: red;
}
<a class="flower big" href="http://example.net/dir/flowers/spring.php">Will be red because has both classes in order and /dir/flowers/</a>
<a class="flower big" href="http://example.net/dir/flowers/winter.php">Will be red because has both classes in order and /dir/flowers/</a>
<a class="flower big" href="http://example.net/dir/flowers/fall.php">Will be red because has both classes in order and /dir/flowers/</a>
<a class="plant big" href="http://example.net/dir/flowers/spring.php">Won't be red because hasn't classes in order even having  the /dir/flowers/</a>
<a class="flower big" href="http://example.net/dir/foobar/fall.php">Won't be red because hasn't the /dir/flowers/ even having the correct classes</a>


更新

如果你想在 a 中有更多的类或者改变这两个类的顺序,那么你需要在 CSS 中选择不同的 a ,一些像 .flower.big.big.flower 就可以了。

a {
  display: block
}
.big.flower[href*="/dir/flowers/"] {
  color: red;
}
<a class="flower big foobar" href="http://example.net/dir/flowers/spring.php">Will be red because has both classes in link and /dir/flowers/</a>
<a class="big flower" href="http://example.net/dir/flowers/winter.php">Will be red because has both classes in link and /dir/flowers/</a>
<a class="foo bar classes big flower" href="http://example.net/dir/flowers/fall.php">Will be red because has both classes in link and /dir/flowers/</a>
<a class="plant big" href="http://example.net/dir/flowers/spring.php">Won't be red because hasn't classes in link  even having  the /dir/flowers/</a>
<a class="flower big" href="http://example.net/dir/foobar/fall.php">Won't be red because hasn't the /dir/flowers/ even having the correct classes</a>

关于html - 匹配包含部分 URL 和特定类的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37230111/

相关文章:

css - 相对于其他元素的 100% 高度

html - ios文本输入: cursor misplaced

css - 通过 CSS 设计 SOS 点功能

javascript - 如何减少元素边框的长度?

html - 加载时触发动画,移除类时动画到默认状态

javascript - 在html中设置数字格式?

html - :empty and :blank with comment inside

jquery - 表行/数据上的第 n 个 child (偶数)

css:如何定位p a img

jquery - 如何在 jquery 中的两个类之间切换?