js实现窗口抖动
实现窗口抖动效果
窗口抖动效果可以通过CSS动画结合JavaScript实现。以下是两种常见方法:
方法一:使用CSS动画和JavaScript触发
定义抖动动画关键帧,通过JavaScript添加/移除类名触发动画。
.shake {
animation: shake 0.5s cubic-bezier(.36,.07,.19,.97) both;
}
@keyframes shake {
10%, 90% { transform: translate3d(-1px, 0, 0); }
20%, 80% { transform: translate3d(2px, 0, 0); }
30%, 50%, 70% { transform: translate3d(-4px, 0, 0); }
40%, 60% { transform: translate3d(4px, 0, 0); }
}
function shakeElement(element) {
element.classList.add('shake');
element.addEventListener('animationend', () => {
element.classList.remove('shake');
}, {once: true});
}
// 使用示例
const windowElement = document.documentElement;
shakeElement(windowElement);
方法二:纯JavaScript实现
通过定时器连续修改元素位置实现抖动效果。
function shakeWindow(intensity = 5, duration = 500) {
const startTime = Date.now();
const originalPosition = window.scrollX;
function updateShake() {
const elapsed = Date.now() - startTime;
if (elapsed >= duration) {
window.scrollTo(originalPosition, window.scrollY);
return;
}
const progress = elapsed / duration;
const currentIntensity = intensity * (1 - progress);
const offset = Math.random() * currentIntensity * 2 - currentIntensity;
window.scrollTo(originalPosition + offset, window.scrollY);
requestAnimationFrame(updateShake);
}
updateShake();
}
// 使用示例
shakeWindow(10, 700);
方法三:jQuery简化实现
如果项目中已使用jQuery,可以简化实现过程。

function shakeWindow() {
$('html, body')
.animate({left: '-=10px'}, 50)
.animate({left: '+=20px'}, 100)
.animate({left: '-=20px'}, 100)
.animate({left: '+=20px'}, 100)
.animate({left: '-=10px'}, 50);
}
// 使用示例
shakeWindow();
注意事项
- 方法一性能最佳,推荐优先使用CSS动画方案
- 抖动强度可通过修改translate3d值或intensity参数调整
- 移动端使用时注意性能影响
- 避免在用户交互过程中频繁触发抖动效果






