在CSS3屬性選擇器中,E[attr*=val]
和E[attr~=val]
是很容易混淆的,舉個栗子:
<style type="text/css">
.demo{width: 300px;border:1px solid #ccc;padding: 10px;overflow: hidden;margin: 20 auto;}
.demo a {float: left;display: inline-block;height: 50px;line-height: 50px;width: 50px;border-radius: 10px;text-align: center;background: #aac;color: blue; font: bold 20/50px arial;margin-right:5px;text-decoration: none;margin: 5px;}
</style>
<div class="demo">
<a class="links item" title="website link">1</a>
<a class="links item" title="open the website">2</a>
<a class="links item" title="close the website">3</a>
<a class="linksitem last" title="websiteitem link">4</a>
</div>
使用E[attr*=val]
,即:a[class*=links]{background: green;}
,此時,我們是給所有class不管是“links”,還是“linksitem”,標籤a1、a2、a3、a4背景都變成綠色了,如圖:
然後,我們來使用E[attr~=val]
吧!!即:a[title ~=website]{background: yellow;}
,我們來觀察,發現...直接上圖吧!:
咦....!!發現有木有前三個標籤都變成黃色,只有最後一個沒有變黃,我們上去看一下第四個標籤的
title
程式碼:title="websiteitem link"
,原來第4個的title
是"websiteitem
,所以我們來總結一下E[attr*=val]
和E[attr~=val]
的區別:
他們的區別是:E[attr*=val]
匹配的是元素屬性值中只要包含val
字串就可以了,而E[attr~=val]
匹配的是元素屬性值中要包含“val
”,並不僅是字串。例如a[title~=website]
屬性中的website
是一個單詞,而a[title*=links]
中的links不一定是一個單詞,就如上面的示例中,可以是“linksitem
”。