ch5 对链接应用样式

简单的链接样式

对链接应用样式最容易的方式是:使用锚类型选择器,例如 a {color:red;}

  • 链接伪类选择器
    1、:link:寻找没有被访问过的链接
    2、:visited:寻找被访问过的链接
  • 动态伪类选择器:
    1、:hover:寻找鼠标悬停处的元素
    2、:active:寻找被激活的元素,激活发生在链接被单击时
    3、:focus:寻找获得焦点的元素
    以上三种不限于链接,也可应用于其他元素,例如按钮、输入框等
    选择器的次序非常重要,如果反过来,鼠标悬停和激活样式将不起作用,为确保这种情况不会发生,最好按照以下次序应用链接样式:
a:link, a:visited, a:hover, a:focus, a:active

为链接目标设置样式

除了可以连接到特定的文档之外,还可以使用片段标识符的链接链接到页面的指定部分,实现方法:在href的末尾加上#要链接元素的id,使用:target伪类为目标元素设置样式。

<div class="comment" id="comment1">
  <h2>Comment #1</h2>
  <p>Lorem ipsum dolor sit amet</p>
  <p><a href="#comment2">comment2</a></p>
</div>
<div class="comment" id="comment2">
  <h2>Comment #2</h2>
  <p>Nulla facilisi. </p>
  <p><a href="#comment3">comment3</a></p>
</div>
<div class="comment" id="comment3">
  <h2>Comment #3</h2>
  <p>Praesent odio lacus.</p>
  <p><a href="#comment1">comment1</a></p>
</div>

<style>
.comment {
    background-color: #ddd;
    border: 1px solid #ccc;
    width: 50em;
    padding: 1em;
    margin: 2em 0;
    background-image: none;
}
/* 关键技术 */
.comment:target {
    background-color: yellow;
</style>

上述代码实现的结果如下,点击Comment #1下面的comment2链接时,它的目标元素Comment#2的背景色变为黄色:

突出显示不同类型的链接

一般的链接很难看出是指向本站点的另一个页面还是纸箱另一个站点,所以需要让外部链接看起来不一样,使用[att^=val]属性选择器寻找外部链接,如下:

<p><a href="http://www.google.com/">This is an external link</a></p>
<p>And here is a reasonably long line of text containing  an <a href="http://www.andybudd.com/index.php">absolute internal link</a>, 
some text, an <a href="http://www.yahoo.com/">an external link</a>,
 some more text, a <a href="css-button.htm">relative internal link</a> and then some more text.</p>
<p>Contact me by <a href="mailto:info@andybudd.com">email</a><br />
Send me an <a href="aim:goim?screenname=andybudd">instant message</a> using AIM/iChat.</p>
</p>
<style>
a[href^="http:"] {
  background: url(img/externalLink.gif) no-repeat right top;
  padding-right: 10px;
}
/*上述会突出显示所有外部链接,但是也会选中使用绝对URL而不是相对URL的内部链接,所以需要重新设置指向自己站点的所有链接,
删除它们的外部链接图标*/
a[href^="http://www.andybudd.com"], a[href^="http://andybudd.com"]  {
  background-image: none;
  padding-right: 0;
}
/*邮件链接图标*/
a[href^="mailto:"] {
  background: url(img/email.png) no-repeat right top;
  padding-right: 15px;
}
/*AIM即时消息协议*/
a[href^="aim:"] {
  background: url(img/im.png) no-repeat right top;
  padding-right: 15px;
}
</style>
上述代码结果:
上述代码结果

突出显示可下载的文档和提要:使用[att$=val]属性选择器

/*以下代码可以告诉访问者它们是下载链接而不是另一个页面的链接*/
a[href$=".pdf"]{
  background: url(img/pdfLink.gif) no-repeat right top;
  padding-right: 15px;
}
a[href$=".doc"]{
  background: url(img/wordLink.gif) no-repeat right top;
  padding-right: 15px;
}

 

posted @ 2017-10-26 19:26  L_mj  阅读(242)  评论(0编辑  收藏  举报