<head>
<style>
.thisOne{ background: red;}
div[class*="thisTwo"] { background: green}
</style>
</head>
<body>
<div class="thisOne">
<p id="hello">Hello World</p>
</div>
<div class="thisTwo">
<p id="hello">Hello World</p>
</div>
</body>
我想知道这种选择方式有何不同:
.thisOne{ background: red;}
div[class*="thisTwo"] { background: green}
他们做同样的工作,对吧?为什么双选择器会更先进?
答案 0 :(得分:2)
实际上,他们没有做同样的事情。与div.thisTwo
完全相同的属性选择器是div[class~="thisTwo"]
。请注意使用~
而不是*
。更不用说您的.thisOne
选择器也缺少前面的div
。
div[class*="thisTwo"]
选择其div
属性包含字符串class
的任何thisTwo
,但它不会考虑将此字符串分隔的任何空格来自其他课程。它只是在属性值的任何地方查找字符串。
这意味着它将匹配以下div.thisTwo
无法匹配的元素,因为它只有一个类 thisOne-thisTwo
,其中包含字符串{{1} },而不是两个单独的类 thisTwo
和thisOne
:
thisTwo
答案 1 :(得分:1)
不,不。第一个将选择类名为thisOne
的任何元素。第二个将选择其类包含术语div
的任何thisTwo
。