標籤雲(Tag Cloud)常用於部落格側邊欄、文章分類展示。透過隨機分配顏色與字體大小,讓視覺更豐富、重點更突出。本文展示純 jQuery + CSS 實現的隨機多彩標籤雲。
<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>
<!-- 更多標籤連結 -->
</div>
</div>
<style>
body, a { font-size:13px; }
a { color:#333; text-decoration:none; }
.taglist { width:250px; overflow:hidden; border:#ddd solid 1px; }
.taglist .tit { height:24px; line-height:24px; background:#565662; }
.taglist .tit a { padding-left:8px; color:#fff; }
#tags a { height:26px; line-height:26px; padding-right:6px; display:inline-block; }
/* 10 組預設隨機樣式 */
#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>
<script src="jquery-1.6.4.js"></script>
<script>
$(document).ready(function() {
var tags_a = $("#tags a");
tags_a.each(function() {
// 產生 0~9 隨機整數
var rand = parseInt(Math.random() * 10);
$(this).addClass("tags" + rand);
});
});
</script>
.tags0 ~ .tags9 十組不同顏色/字級組合。Math.random() * 10 取 0~9.999,parseInt 取整得 0~9。$(this).addClass("tags" + rand) 將隨機類別套用至每個 <a>。若標籤帶有使用次數(權重),可依權重區間分配樣式,而非純隨機:
// 假設資料結構:[{text: 'JS', count: 120}, {text: 'CSS', count: 80}, ...]
var maxCount = Math.max(...data.map(d => d.count));
var minCount = Math.min(...data.map(d => d.count));
data.forEach(item => {
// 將 count 映射到 0~9 樣式等級
var level = Math.floor(9 * (item.count - minCount) / (maxCount - minCount || 1));
$('').text(item.text).addClass('tags' + level).appendTo('#tags');
});
<style>
:root {
--tag-colors: #C00, #030, #00F, #F06, #60F, #090, #F90, #900, #009, #666;
--tag-sizes: 0.9rem, 1rem, 1.1rem, 1.2rem, 1.3rem, 1.4rem, 1.5rem, 1.6rem, 1.7rem, 1.8rem;
}
.tag-cloud a {
--i: 0; /* 由 JS 設定 */
color: var(--tag-colors); /* 需配合 JS 設定單一色值 */
font-size: var(--tag-sizes);
display: inline-block; margin: 2px 4px; text-decoration: none;
}
</style>
<div class="tag-cloud" id="tags"></div>
<script>
const colors = ['#C00','#030','#00F','#F06','#60F','#090','#F90','#900','#009','#666'];
const sizes = ['0.9rem','1rem','1.1rem','1.2rem','1.3rem','1.4rem','1.5rem','1.6rem','1.7rem','1.8rem'];
document.querySelectorAll('#tags a').forEach(a => {
const i = Math.floor(Math.random() * 10);
a.style.color = colors[i];
a.style.fontSize = sizes[i];
});
</script>
隨機多彩標籤雲的核心在於 預定義樣式組合 + 隨機索引 + 動態加類別。傳統 jQuery 寫法簡潔易懂;現代專案可改用 CSS 變數 + Vanilla JS,移除 jQuery 依賴並獲得更佳效能與維護性。