JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>daisyUI 單一卡片主題切換</title>
<!-- ✅ 直接使用 daisyUI CDN -->
<link href="https://cdn.jsdelivr.net/npm/daisyui@4.12.10/dist/full.min.css" rel="stylesheet" type="text/css" />
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="min-h-screen flex flex-col items-center justify-center gap-6 p-6 bg-gray-100">
<button id="changeTheme" class="btn btn-primary">
🎨 隨機更換卡片風格
</button>
<!-- ✅ 在 card 外層加 data-theme 屬性 -->
<div id="cardContainer" data-theme="cupcake" class="card w-96 bg-base-100 shadow-xl transition-all duration-300">
<figure><img src="https://picsum.photos/400/200" alt="隨機圖片"></figure>
<div class="card-body">
<h2 class="card-title">daisyUI Card</h2>
<p>只改變卡片風格,不影響整個頁面。</p>
<div class="card-actions justify-end">
<button class="btn btn-secondary">了解更多</button>
</div>
</div>
</div>
<script>
const themes = [
"light","dark","cupcake","bumblebee","emerald","corporate",
"synthwave","retro","cyberpunk","valentine","halloween",
"garden","forest","aqua","lofi","pastel","fantasy",
"wireframe","black","luxury","dracula"
];
document.getElementById('changeTheme').addEventListener('click', () => {
const randomTheme = themes[Math.floor(Math.random() * themes.length)];
// ✅ 只改變卡片的 data-theme,而不是整個 html
document.getElementById('cardContainer').setAttribute('data-theme', randomTheme);
console.log("切換卡片主題:", randomTheme);
});
</script>
</body>
</h