CSS3屬性選擇器之:教你區分E[attr*=val]和E[attr~=val]的使用方法!!

Mr.柯小浩發表於2017-09-18

在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[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”。

相關文章