任何一个HTML标签都会有属性存在,而且每个属性都具有属性值。
例如img标签:
<img src="http://wwww.rutongnet.com/img/global/RtItn_logo.gif" alt="我们网站的LOGO" />
代码中src,alt都是img标签的属性,引号中的内容分别为它们的属性值。每个属性都必须带有属性值。
了解了HTML标签具有属性的特性后,这会来介绍如何利用属性选择符对标签进行样式定义。
属性选择符的格式是标签元素后紧跟一对中括号,中括号里的内容是该标签元素的属性或表达式。
属性选择符可分为4种模式:
- E[attr]
- E[attr="value"]
- E[attr~="value"]
- E[attr|="value"]
E代表任何一个HTML标签,attr代表E标签的任意一个属性,value代表这个属性的值。
一、E[attr]将匹配具有attr属性的E标签元素,忽略其属性值。
例如:我们想要把页面中所有带ID的属性的标签都定义样式。可以这样写:
<style type="text/css">
*[id]{color:Red;}
</style>
<span id="span1">span有ID</span>
<p>p</p>
<h1 id="h">h1有ID</h1>
<h3>h3</h1>
<h2>h2</h1>
*[id]{color:Red;}
</style>
<span id="span1">span有ID</span>
<p>p</p>
<h1 id="h">h1有ID</h1>
<h3>h3</h1>
<h2>h2</h1>
效果大家可能也猜到了span标签和h1标签全部为红色显示。
截图:
二、E[attr="value"]匹配具有“attr”属性且属性值为“value” 的E标签元素。
例如我这里要定义type属性值为text的input标签的样式。
则可以这样写:
<style type="text/css">
input[type="text"]
{
color:Blue;
}
</style>
<input type="text" value="My God" />
input[type="text"]
{
color:Blue;
}
</style>
<input type="text" value="My God" />
效果:
三、E[attr~=value]匹配具有attr属性且其中值包含value的E元素。注意了值之间要有空格隔开。
<style type="text/css">
span[title~="rutongnet"]
{text-decoration:underline;}
</style>
<span title="rutongnet css">title属性值为rutongnet css的span标签</span>
span[title~="rutongnet"]
{text-decoration:underline;}
</style>
<span title="rutongnet css">title属性值为rutongnet css的span标签</span>
这段代码的效果如下图:
四、E[attr|=value]匹配具有attr属性且属性值必须是以 value 开始及使用连字符(-) 分隔的E标签。
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
<style type="text/css">
p[title|="rutongnet"]
{
text-decoration:underline;
color:Aqua;
}
</style>
<p title="rutongnet css">title属性值为rutongnet css的p标签</p>//没有连字符所以不匹配
<p title="css rutongnet">title属性值为css rutongnet的p标签</p>//不匹配,其以CSS开头
<p title="rutongnet+css">title属性值为rutongnet+css的p标签</p>//不匹配,其未使用连字符
<p title="rutongnet-css">title属性值为rutongnet-css的p标签</p>//匹配成功
<p title="rutongnetcss">title属性值为rutongnetcss的p标签</p>//不匹配未使用连字符
p[title|="rutongnet"]
{
text-decoration:underline;
color:Aqua;
}
</style>
<p title="rutongnet css">title属性值为rutongnet css的p标签</p>//没有连字符所以不匹配
<p title="css rutongnet">title属性值为css rutongnet的p标签</p>//不匹配,其以CSS开头
<p title="rutongnet+css">title属性值为rutongnet+css的p标签</p>//不匹配,其未使用连字符
<p title="rutongnet-css">title属性值为rutongnet-css的p标签</p>//匹配成功
<p title="rutongnetcss">title属性值为rutongnetcss的p标签</p>//不匹配未使用连字符
上面这段代码效果为:
这篇文章介绍一下属性选择符,这篇文章千呼万唤始出来的原因,主要是属性选择符先前我自己也用得也太多。原因只有一个IE6不支持。而我们的产品有大量的IE6用户。
文章写得太简了,有问题直接留言吧?每留必回。