跳至主要内容

CSS 圖層魔術

· 閱讀時間約 2 分鐘

今天做了一個很白爛的圖層魔術

按下按鈕後,帽子先往下蓋住,再掀開,裡面會冒出兔子、青蛙,或者乾脆什麼都沒有。

說明

  • position: relative:讓舞台變成絕對定位元素的參考點。
  • position: absolute:把每張圖放到指定座標。
  • z-index:控制遮擋順序。帽子要蓋住角色,所以層級要最高。
  • transition:當 top 被改變時,自動產生移動動畫,做出「蓋住 -> 掀開」的節奏。
  • display: none 雖然簡單,但不能直接做淡入淡出;如果需要更順的切換,可以改用 opacity 搭配 visibility
  • 舞台尺寸最好固定,不然不同圖片尺寸可能會讓圖層位置跑掉。

程式碼

注意

圖片請自備~(或者去文章內右鍵下載)

<div class="magic-stage">
<style>
.magic-stage { position: relative; width: 300px; height: 400px; margin: 0px auto; text-align: center; }
.magic-stage img { position: absolute; transition: top 0.6s ease-in-out; }
.magic-stage .magic-table { width: 280px; left: 10px; top: 250px; z-index: 1; }
.magic-stage .magic-hat { width: 160px; left: 70px; top: 0; z-index: 3; }
.magic-stage .magic-rabbit { width: 80px; left: 110px; top: 170px; z-index: 2; display: none; }
.magic-stage .magic-frog { width: 80px; left: 110px; top: 195px; z-index: 2; display: none; }
.magic-stage .active { display: block; }
.magic-stage button { margin-top: 340px; padding: 10px 30px; cursor: pointer; border: 2px solid #6200ee; border-radius: 4px; background: #6200ee; color: white; font-size: 16px; font-weight: bold; transition: 0.2s; }
.magic-stage button:disabled { background: #ccc; border-color: #ccc; cursor: not-allowed; }
</style>

<img src="table.png" class="magic-table" alt="magic-table">
<img src="hat.png" class="magic-hat" alt="magic-hat">
<img src="rabbit.png" class="magic-rabbit" alt="magic-rabbit">
<img src="frog.png" class="magic-frog" alt="magic-frog">
<button class="magic-button" onclick="performMagic()">Magic</button>

<script>
let magicStep = 0;

function performMagic() {
const magicStage = document.querySelector('.magic-stage');
const magicHat = magicStage.querySelector('.magic-hat');
const magicRabbit = magicStage.querySelector('.magic-rabbit');
const magicFrog = magicStage.querySelector('.magic-frog');
const magicButton = magicStage.querySelector('.magic-button');

magicButton.disabled = true;
magicHat.style.top = "140px";

setTimeout(() => {
magicRabbit.classList.remove('active');
magicFrog.classList.remove('active');

if (magicStep === 0) {
magicRabbit.classList.add('active');
} else if (magicStep === 1) {
magicFrog.classList.add('active');
}

magicStep = (magicStep + 1) % 3;

magicHat.style.top = "0px";
setTimeout(() => magicButton.disabled = false, 600);
}, 1250);
}
</script>
</div>