純原生 JS 實現點擊觸發的彈窗抖動效果,結合隨機背景色變化,展示定時器、動畫幂、樣式操作綜合應用。
<!doctype html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<title>彈窗抖動特效</title>
<style>
.box {
width: 300px; height: 150px;
position: absolute;
text-align: center; line-height: 150px;
font-weight: bold; cursor: pointer;
}
#dv { left: 200px; top: 100px; background: red; }
#dv2 { left: 600px; top: 100px; background: yellow; }
</style>
</head>
<body>
<div id="dv" class="box">點我呀</div>
<div id="dv2" class="box">點我呀</div>
<script>
window.onload = function() {
// 工具:隨機整數 [min, max]
const rand = (min, max) => min + Math.round(Math.random() * (max - min));
// 獲取元素
const dv = document.getElementById('dv');
const dv2 = document.getElementById('dv2');
// 抖動位移序列:20, -20, 18, -18 ... 2, -2
const shakeOffsets = [];
for (let i = 20; i > 0; i -= 2) {
shakeOffsets.push(i, -i);
}
// 1. 隨機變色定時器
setInterval(() => {
const color = `rgb(${rand(0,255)}, ${rand(0,255)}, ${rand(0,255)})`;
dv.style.backgroundColor = color;
}, 130);
// 2. 通用抖動函數
function shake(el, attr, onEnd) {
let index = 0;
const startVal = parseInt(getComputedStyle(el)[attr]);
const timer = setInterval(() => {
if (index >= shakeOffsets.length) {
clearInterval(timer);
onEnd?.();
return;
}
el.style[attr] = startVal + shakeOffsets[index] + 'px';
index++;
}, 50);
}
// 3. 獲取樣式兼容封裝
function getStyle(el, prop) {
return el.currentStyle ? el.currentStyle[prop] : getComputedStyle(el)[prop];
}
// 4. 綁定點擊:先左抖動,再上抖動,最後顯示顏色
[dv, dv2].forEach(box => {
box.onclick = () => {
shake(box, 'left', () => {
shake(box, 'top', () => {
box.innerHTML = `我是${getStyle(box, 'backgroundColor')}色`;
});
});
};
});
};
</script>
</body>
</html>
[20,-20,18,-18,...,2,-2] 模擬物理阻尼效果。onEnd 實現水平→垂直→文本更新的序列執行。currentStyle (IE) vs getComputedStyle (標準)。rgb(r,g,b) 格式,每通道 0-255。requestAnimationFrame 替換 setInterval 獲得更流暢動畫。shakeElement(el, {x: true, y: true})。transition 實現平滑過渡(需配合 transform 而非 left/top)。本例展示了原生 JS 實現視覺特效的完整思路:數據驅動動畫(位移數組)、狀態機控制流程(回調串聯)、兼容性封裝。理解此模式,可輕鬆構建各類交互動畫。