JavaScript的有用超链接

在那里,您可以愉快地浏览网站; 您单击一个链接,突然发现自己在另一个被要求下载文件的站点。 那里发生了什么? 烦人,不是吗? 必须有一种更好的方法来向您的访问者指示链接的去向以及文件的类型。 因此,为帮助解决此烦恼,我编写了一些JavaScript和CSS,在链接后(根据文件扩展名和位置而定)添加了很少的图标,以向用户指示他们将要处理的文档类型。加载。

图标链接

您可以在此处下载代码,查看示例

简要

创建此功能时,主要考虑因素是:

  1. 简单–必须易于使用
  2. 正常降级–在CSS或/和JavaScript被禁用的情况下
  3. 最少地使用文件–只有一个JavaScript和一个CSS文件
  4. 使其尽可能即插即用–可以将其快速添加到网站
  5. 限制代码总量
  6. 与所有现代浏览器(包括IE6)兼容
为什么要从纯CSS解决方案转变呢?

您已经可以使用属性选择器在CSS中完成此操作。 这是一个例子:

a[href$='.doc'] { 
 display: inline-block;
 padding-left: 16px;
 background: transparent url(images/icon_doc.gif) center right no-repeat;
}

那么,当大多数现代浏览器仅使用CSS来显示图标时,为什么还要用脚本来实现呢?

答案很简单:IE6。 除IE6外,所有不错的浏览器都支持CSS3属性选择器……。 CSS的这种脚本编写使得IE6可以很好地播放。 实际上,它甚至可以在IE5.5中使用。

灵感与信誉

在开始之前,我想感谢famfamfam的Mark James出色且免费的Silk图标,我们将在本文中使用它。

丝绸图标

另外,应归功于应得的荣誉:本文的灵感来自Alexander Kaiser的文章CSSIconize Textlinks with CSS ,而文章的灵感又来自Ask CSS Guy的CSS 超链接提示 。 此外,我使用了一些由SitePoint自己的James Edwards编写的出色功能,以及另外两个选自Core JavaScript库 (由Kevin Yank和Cameron Adams编写)的功能,并在SitePoint书《 Simply JavaScript 》中永存。

那么它是怎样工作的?

简而言之,我们将获取页面中的所有链接,计算出链接到的文件扩展名,然后在链接后添加适当的图标。 真好

要使其全部正常工作,涉及三个文件:

  1. 包含链接的HTML页面index.html
  2. 包含图标类iKonize.css的CSS文件
  3. 将CSS类和图标添加到链接的JavaScript文件iKonize.js
快速启动方法

现在,如果您想回避“为什么”和“为什么”,而只想将其添加到页面中,则为以下简短版本:

  1. 在页面标题中添加指向JavaScript和CSS文件的链接(更改文件引用以适合您的站点设置)。
    <link type="text/css" rel="stylesheet" href="iKonize.css"/>
    <script type="text/javascript" src="iKonize.js"></script>
  2. 将您的icons文件夹放在您的网站上,并确保iKonize.css文件中的url引用正确。
  3. 从结束body标记之前包含的脚本标记调用JavaScript函数iKonize ,如下所示:
    <script type="text/javascript">iKonize();</script>

看–我告诉过您,使用起来很简单!

为简单起见,我选择在DOM加载后从HTML内部调用该函数。 还有其他使用JavaScript来实现此目的的方法,但它们超出了本文的范围。

完整说明

让自己感到舒适,我们将深入研究内部工作原理。

组态

本着使事情变得简单的精神,大多数设置已经为您完成。 仅在需要更改图标或文件扩展名时才需要更改配置。 有两个地方可以进行这些更改:JavaScript(iKonize.js)和CSS文件(iKonize.css)。

配置iKonize.js

在文件顶部,您将看到所有配置变量: classPrefixclassExternalclassIconLoc

 classPrefix is the prefix you want to give the individual CSS classes. Use this to prevent any conflicts with any existing CSS classes. The default is iKon_ .

classExternal
externalIconLoc

Which links will receive an icon?

To define what type of file the link goes to, we'll look at the file extension. The file types are split out into two groups: those that have unique icons, such as torrent files, and those that will share the same icon, but have different file extensions, such as Flash files (.fla and .swf).

Grouping file extensions that share the same icon saves you having hundreds of CSS classes and icons. To achieve this I have created two arrays.

The first array, IndividualClassArray , holds the file extensions of all the links with individual icons. The base of the CSS class name is the same as the file extension. That is, a text file is referenced with ' txt ' and the CSS class name is the classPrefix (set earlier) and 'txt' the base CSS class name, making a CSS class called 'iKon_txt' in this case.

IndividualClassArray = Array('txt', 'xls', 'css', 'torrent');

The second array, classArray , is actually a multidimensional array, but don't let that put you off. Basically, it's a group of individual arrays grouped according to the kind of icon we'd like to use. The first item in this array is IndividualClassArray (this array must always be the first array). The following arrays are similar to the previous array with one important difference: the first item in each of the arrays is the name of the CSS class that will be used, and the following items are the file extensions which need that class. In the following example the .swf and .fla file extensions will be associated with the 'flash' CSS class.

classArray = Array(  
IndividualClassArray,  
Array('flash', 'swf', 'fla')  
);

Note: File extensions exclude the dot, that is, xls not .xls.

For maximum portability, the actual CSS class name used will have a prefix such as 'iKon_', which we configured earlier - but in these arrays we always exclude the prefix. So a Flash CSS class is always referred to as 'flash' rather than 'iKon_flash'.

External Links

To figure out whether a link is an external site, we need to know the host name of the current page.

For this we use:

url = parseURL(qualifyHREF(document.location.href)).hostname;

This takes the current document's location and gets the domain name using the qualifyHREF function to make sure we have a fully qualified address and the parseURL function to get the host name. (Both of these functions were written by our resident JavaScript guru, Brothercake, and covered in his blog post ). Later, when we add the classes for the external links, we'll use this host name to work out whether the link is external to our site.

The Code That Actually Does the Work

Now we need to get all the links from the page using document.getElementsByTagName("a"), and determine the file extension of the link.

We do this by using the functions parseURL and qualifyHREF again.

First, take the href value of the a element:
linkHref = aElements[iv].href;

Next, parse the value to gain more information about the link:
oUrl = parseURL(qualifyHREF(linkHref));

Then get the extension for the link:
fileExt = oUrl.extension;

Then, we need to loop through these links and work out whether they need an icon. This is where it starts to become a little bit trickier. We need to loop through classArray and each of the arrays it contains. We do this by running a loop within a loop. Yes, that’s a loop, in a loop, in a loop! This hairy piece of code looks like this:

aElements = document.getElementsByTagName("a");  
iElements = aElements.length;  
 
for (iv = 0; iv < iElements; iv++) {  
 iLen = classArray.length;  
 for (ii = 0; ii < iLen; ii++) {  
     iArr = classArray[ii].length;  
       for (i = 0; i < iArr; i++) {  
           // Do we need to add an icon?  
         }  
    }  
}

Does this link require an icon?

To find out if we need to add an icon, we’ll compare the file extension of the link with each of the extensions listed in our arrays.

 if (fileExt == classArray[ii][i]) {      
   if (ii === 0) {  
      linkClass = fileExt;  
   }  
   else {  
      linkClass = classArray[ii][0];  
   }  
   bFound = true;  

Now we know if the link needs an icon, and which class it needs. We'll add that class using the addClass function we've grabbed from the Core JavaScript Library.
if (bFound && linkClass !== '') {  
   addClass(aElements[iv], classPrefix + linkClass);  
}  

Links to External Sites

Working out if the link is to an external site is just a case of comparing the URL host name we determined earlier with the URL we set in the configuration area.

if (oUrl.hostname.indexOf(url) == -1) { // not our url  
   bExternal = true;  
}

If it's true, we'll append a new image element in the anchor, add a source and ID, and then add an alt and title attribute for the image. We add the extra icon rather than just assigning a class to clearly show that this link goes to another site, as well as adding title and alt attributes to the icon.

if (bExternal) { //  an external link  
  img = document.createElement('img');  
  img.id = 'Newimg' + iv;  
  img.src = externalIconLoc;  
  img.alt = 'external site';  
  img.title = 'links to an external web site';  
  void (aElements[iv].appendChild(img));  
  oimg = document.getElementById("Newimg" + iv);  
  addClass(oimg, classExternal);  
}

The CSS Classes

Let's move back to the CSS file now.

Here is our CSS class to add the icon to .doc files. Notice the class name is prefixed with ' iKon_ ' and then the file extension ' doc '. This class basically puts a bit of padding in the top and bottom, and to the right of the link. It then adds a background image of the icon into that space.

.iKon_doc {  
 padding: 5px 20px 5px 0;  
 background: transparent url(icons/icon_doc.gif) no-repeat center right;  
}

For our external link icons, we'll use a slightly different class structure. We add some padding top and bottom to make sure our icon is borderless.

.iKon_external{   
 padding: 5px 0 0 5px;  
 border: 0;  
}

If you changed the classPrefix variable, don't forget to alter these class names to match.

Limitations

The link must have a file extension to have an icon assigned to the link (unless it's an external site). The script also doesn't recognize query string- based navigation links. If CSS is disabled, then only the external link icon will display and if JavaScript is disabled, then there are no visible changes to the page.

Conclusion

iKonize is a quick and easy way to add visually meaningful icons after links. The script works in IE5.5+ and can work independent of CSS3 attribute selectors. As you might expect, the script degrades well and is easily configured. I hope you find it useful!

From: https://www.sitepoint.com/helpful-hyperlinks-javascript/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值