標籤雲是展示網站熱門主題、引導訪客探索內容的經典 UI 元件。它不僅能直觀呈現站點覆蓋範圍,還能讓讀者一鍵跳轉至高頻話題。更妙的是,標籤雲可應用於任何與頻率相關的場景:文章、圖片、影片、產品標籤等。本教學將帶你用 jQuery 1.4.2、PHP、MySQL 與 AJAX 從零構建一個動態標籤雲。
tags 儲存標籤名與頻率CREATE DATABASE tagcloud;
USE tagcloud;
CREATE TABLE tags (
tag VARCHAR(100),
frequency INT
);
INSERT INTO tags (tag, frequency) VALUES
('jQuery', 200), ('javascript', 190), ('css', 180), ('yui', 170),
('html', 150), ('design', 120), ('php', 110), ('mysql', 100),
('ajax', 90), ('json', 90), ('security', 70), ('browsers', 60),
('tutorial', 60), ('semantics', 50), ('widgets', 40), ('oop', 30),
('wordpress', 20), ('debugging', 20), ('seo', 10);
<?php
$host = "localhost";
$user = "root";
$password = "root";
$database = "tagcloud";
$conn = mysql_connect($host, $user, $password);
mysql_select_db($database, $conn);
$query = mysql_query("SELECT * FROM tags");
$json = "({ tags:[";
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$row = mysql_fetch_assoc($query);
$json .= "{tag:'" . $row["tag"] . "',freq:'" . $row["frequency"] . "'}";
if ($x < mysql_num_rows($query) - 1) $json .= ",";
else $json .= "]})";
}
// JSONP 回調
$callback = $_GET['callback'];
echo $callback . $json;
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "https://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="tagcloud.css">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>jQuery Tag Cloud</title>
</head>
<body>
<div id="tagCloud">
<h2>Tag Cloud</h2>
</div>
<script src="jquery-1.4.2.min.js"></script>
<script>
$(function() {
$.getJSON("https://localhost:9000/jquery/tagcloud.php?callback=?", function(data) {
// 處理 data.tags 陣列,動態生成標籤元素並根據 freq 設定字級/顏色
// 此處略過具體渲染邏輯,請參考完整原始碼
});
});
</script>
</body>
</html>
mysqli 或 PDO,並做好輸入過濾。font-size/color。完整原始碼可下載:tag cloud 源代碼包。動手試做,幾分鐘即可為網站加上動態標籤雲!