標籤雲如果每個都是同樣的顏色與字級,看起來會很呆板。實作方式其實很單純:預先寫好幾組不同顏色、字級的 CSS class,再用 JavaScript 為每個標籤隨機掛上一個 class 即可。
<script type="text/javascript" src="jquery-1.6.4.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var tags_a = $("#tags a");
tags_a.each(function () {
var x = 9, y = 0;
var rand = parseInt(Math.random() * (x - y + 1) + y); // 產生 0~9 的整數
$(this).addClass("tags" + rand);
});
});
</script>
這裡刻意只載入一次 jQuery,原範例同時引入本機與 CDN 兩份 jQuery 其實是多餘的,還可能因為版本覆蓋而產生非預期行為。
<style>
body, a { font-size: 13px; }
a { color: #333333; text-decoration: none; }
.taglist { width: 250px; overflow: hidden; border: #dddddd solid 1px; }
.taglist .tit { width: 100%; height: 24px; line-height: 24px; background-color: #565662; }
.taglist .tit a { padding-left: 8px; color: #ffffff; }
#tags a { height: 26px; line-height: 26px; padding-right: 6px; }
#tags .tags0 { }
#tags .tags1 { color: #C00; font-size: 24px; }
#tags .tags2 { color: #030; font-size: 16px; }
#tags .tags3 { color: #00F; }
#tags .tags4 { font-size: 16px; }
#tags .tags5 { color: #C00; font-size: 20px; }
#tags .tags6 { color: #F06; font-size: 20px; }
#tags .tags7 { color: #030; font-weight: bold; font-size: 18px; }
#tags .tags8 { color: #F06; font-weight: bold; }
#tags .tags9 { color: #C00; font-weight: bold; font-size: 16px; }
#tags a:hover { color: #F00; text-decoration: underline; }
.w95 { width: 95%; margin: 0 auto; padding: 6px 0; }
</style>
<div class="taglist">
<div class="tit"><a href="#">TAG 標籤</a></div>
<div class="w95" id="tags">
<a href="#">導覽選單</a>
<a href="#">焦點幻燈片</a>
<a href="#">廣告版位</a>
<a href="#">網頁特效</a>
<a href="#">jQuery 特效</a>
<a href="#">滾動程式碼</a>
<a href="#">下拉選單</a>
<a href="#">隨機數</a>
<a href="#">網頁配色</a>
<a href="#">CSS 幻燈片</a>
</div>
</div>
原本 #tags .tags6{color:#F06 font-size:20px;} 漏了分號,會導致整條規則失效,記得補上。
Math.random() 換成依計數映射的 class 即可。:hover 與 focus 狀態。