Nowadays, I could say tag cloud is a standard component of a blog. Unfortunately, cnblogs.com does not provide this feature. In this post, I would like to introduce a DIY implementation of tag cloud in your blog. DIYers, let's roll.

 

First off, let’s have a look at original tag list.

image

It’s a very typical list. Links follow by post count. Picking up the source code of the first entry, you can see the following structure.

<div id="MyTag">
  ...
  <a href="http://www.cnblogs.com/misaxi/tag/ASP.NET+MVC/">ASP.NET MVC</a>(4)
  ...
</div>

Good, the structure is fairly straightforward. Now, we need to extract the necessary data from existed information.

 

Well, we need to figure out what sort of data we need to collect first. Personally, I think two things are elementary.

  1. Link, of course
  2. The post count under tag used to determine the font size of tag

Since the html code of tag list and the things we want are fixed, we can use this regular expression,

/<a(.*?<\/a>).*?\((\d+)\)/g 

, to help us extract information.

 

Full implementation would be like the following

        function applyTagCloud() {
            var regex = /<a(.*?<\/a>).*?\((\d+)\)/g;

            // get all tags from tag list
            var matches = $('#MyTag').html().match(regex);

            var result = [];

            for (var i = 0, l = matches.length; i < l; i++) {
                // extract link and count from each tag
                result.push(matches[i].replace(regex,

                    function (a, link, count) {
                        // calculate the font size as per post count
                        var fontSize = 0.8 + (count / 10.0);

                        // set font size as 2 if it's larger than 2
                        if (fontSize > 2) {

                            fontSize = 2;
                        }

                        return '<a style="font-size: ' + fontSize + 'em;"' + link;
                    }));
            }

            $('#MyTag').html(result.join(''));
        }

 

After we apply the code above, you can see your new appearance of tag list like this.

image

Actually, we should not it tag list anymore, just call your new pet tag cloud ;p

 posted on 2011-02-05 20:18  助平君  阅读(1244)  评论(6编辑  收藏  举报