用js实现页面暂停
实现页面暂停的JavaScript方法
使用CSS动画暂停
通过JavaScript控制CSS的animation-play-state属性实现页面动画暂停。
// 暂停所有动画
document.querySelectorAll('*').forEach(element => {
element.style.animationPlayState = 'paused';
});
// 恢复动画
document.querySelectorAll('*').forEach(element => {
element.style.animationPlayState = 'running';
});
禁用JavaScript定时器
暂停所有使用setTimeout和setInterval创建的定时器。

let timerIds = [];
// 暂停所有定时器
function pauseTimers() {
let id = setInterval(() => {}, 99999);
while(id--) {
if (id < 1) break;
clearInterval(id);
clearTimeout(id);
timerIds.push(id);
}
}
// 恢复定时器需要重新创建
冻结页面交互
通过覆盖全屏遮罩层阻止用户交互。

function freezePage() {
const overlay = document.createElement('div');
overlay.style.position = 'fixed';
overlay.style.top = '0';
overlay.style.left = '0';
overlay.style.width = '100%';
overlay.style.height = '100%';
overlay.style.backgroundColor = 'rgba(0,0,0,0.5)';
overlay.style.zIndex = '9999';
overlay.id = 'freeze-overlay';
document.body.appendChild(overlay);
}
function unfreezePage() {
const overlay = document.getElementById('freeze-overlay');
if (overlay) {
overlay.remove();
}
}
禁用滚动
通过控制CSS的overflow属性阻止页面滚动。
function disableScroll() {
document.body.style.overflow = 'hidden';
}
function enableScroll() {
document.body.style.overflow = '';
}
综合实现
结合上述方法创建完整的页面暂停功能。
class PagePauser {
constructor() {
this.originalOverflow = '';
this.originalAnimations = [];
}
pause() {
// 记录原始overflow值
this.originalOverflow = document.body.style.overflow;
// 禁用滚动
document.body.style.overflow = 'hidden';
// 暂停CSS动画
document.querySelectorAll('*').forEach(el => {
const animation = getComputedStyle(el).animation;
if (animation && animation !== 'none') {
this.originalAnimations.push({
element: el,
style: el.style.animationPlayState
});
el.style.animationPlayState = 'paused';
}
});
// 添加遮罩层
freezePage();
}
resume() {
// 恢复滚动
document.body.style.overflow = this.originalOverflow;
// 恢复CSS动画
this.originalAnimations.forEach(item => {
item.element.style.animationPlayState = item.style;
});
// 移除遮罩层
unfreezePage();
// 清空记录
this.originalAnimations = [];
}
}
这些方法可以根据具体需求单独使用或组合使用,实现不同程度的页面暂停效果。CSS动画暂停和滚动禁用适用于简单场景,而综合实现则提供了更完整的页面冻结方案。






