js转换外部链接样式

in 未分类

http://yibin.us/Archives/702.aspx

上文提到用css属性选择器有选择性地对链接样式进行控制。
如让所有的外部链接都加一个小图标来标识其是一外部链接。
但用css有弊端:

  1. 只支持FireFox等对web标准支持很好的浏览器。
  2. 只能判断链接,不能判断锚点或javascript。如遇到<a href="javascript:void(0);">就无能为力了。

这里可以结合js来完成,首先写一个样式:
a.other:link,a.other:visited,a.other:active
  {
     background:url("external.gif") no-repeat top right;
     padding-right:15px;
  }

再写一个js,但js要考虑到:

  1. 链接的多样性,如上面提到的javascript、锚点等。
  2. 如果是图片链接,就不要应用样式了。

<script type="text/javascript">
     window.onload = function()
     {
       var aList = document.getElementsByTagName(‘a’);
       var iCount = aList.length;
       for(var i = 0;i<iCount;i++)
       {
      
         if(!chkMyLink(aList[i].href,aList[i].innerHTML))
         {
           aList[i].className =’other’;
         }
       }
     }
   
    //s是链接的url,innerhtml是链接文本
     function chkMyLink(s,innerhtml)
     {
        if(innerhtml.replace( /^\s*/,"").match(/^\<img/gi)) return true;

       var reg = /^http\:\/\//gi;
       if(s.match(reg))
       {
          reg = /^http\:\/\/yibin.us/gi;
          if(s.match(reg))
          {
            return true;
          }
          else
          {
            return false;
          }
       }
      return true;
     }

  </script>

现在可以看到效果了。
初级,老鸟勿笑了

5 Comments

5 Comments

  1. 嘿嘿。自己写的呀?

  2. [quote=老不]
    板凳…

    坐得还真够快
    [quote=icejune]
    嘿嘿。自己写的呀?

    是啊,刚写的,然后就发了:D

  3. use jQuery多省事儿。

  4. 初学阶段,贵在学习:p

Leave a Reply

Using Gravatars in the comments - get your own and be recognized!

XHTML: These are some of the tags you can use: <a href=""> <b> <blockquote> <code> <em> <i> <strike> <strong>