點擊區塊內的文字,整個區塊快速閃爍數次以吸引注意力。常用於遊戲網站、促銷提示、重要通知等互動場景。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>點擊閃爍示範</title>
<style>
#box {
position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);
width: 200px; height: 200px; background: #e74c3c; color: #fff;
font: 16px/200px Arial; text-align: center; letter-spacing: 2px;
cursor: pointer; user-select: none; border-radius: 8px;
box-shadow: 0 4px 20px rgba(0,0,0,0.3);
}
</style>
</head>
<body>
<div id="box">點我試試閃爍效果</div>
<script>
(function() {
var box = document.getElementById('box');
var timer = null;
var count = 0;
var MAX_FLASHES = 7; // 閃爍次數(含初始狀態)
box.addEventListener('click', function() {
if (timer) return; // 防重複觸發
count = 0;
timer = setInterval(function() {
box.style.display = (count % 2 === 0) ? 'none' : 'block';
count++;
if (count >= MAX_FLASHES) {
clearInterval(timer);
timer = null;
box.style.display = 'block'; // 確保最後顯示
}
}, 80);
});
})();
</script>
</body>
</html>
@keyframes flash {
0%, 100% { opacity: 1; }
50% { opacity: 0; }
}
.flashing { animation: flash 160ms steps(1) 7; }
JS 僅需 `box.classList.add('flashing')`,動畫結束用 `animationend` 移除類別。