Swap Active
<section class="flex flex-col items-center justify-center p-8 gap-8">
<div class="flex items-center gap-8">
<!-- 默认状态的交换组件 -->
<label class="swap text-6xl">
<div class="swap-on">🥵</div>
<div class="swap-off">🥶</div>
</label>
<!-- 带 swap-active 类的激活状态交换组件 -->
<label class="swap swap-active text-6xl">
<div class="swap-on">🥳</div>
<div class="swap-off">😭</div>
</label>
</div>
<div class="mt-6 p-4 bg-gray-100 rounded-lg">
<p class="text-gray-700 mb-4">通过 JavaScript 切换 swap-active 类:</p>
<div class="flex gap-4 items-center">
<label id="theme-swap" class="swap text-6xl">
<div class="swap-on">🌙</div>
<div class="swap-off">☀️</div>
</label>
<button id="toggleBtn" class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition">
切换主题
</button>
</div>
</div>
</section>
<style>
.swap {
position: relative;
display: inline-grid;
cursor: pointer;
user-select: none;
}
.swap > * {
grid-column-start: 1;
grid-row-start: 1;
transition-property: opacity, transform;
transition-duration: 300ms;
transition-timing-function: ease-in-out;
}
.swap .swap-on,
.swap .swap-off {
display: grid;
place-items: center;
}
.swap .swap-on {
opacity: 0;
}
.swap .swap-off {
opacity: 1;
}
/* 激活类控制状态 */
.swap.swap-active .swap-on {
opacity: 1;
}
.swap.swap-active .swap-off {
opacity: 0;
}
</style>
<script>
// 通过JavaScript控制swap-active类
document.getElementById('toggleBtn').addEventListener('click', function() {
const themeSwap = document.getElementById('theme-swap');
themeSwap.classList.toggle('swap-active');
});
</script>
Copied to clipboard