← 中文资源

简体中文版本

用 inert 隔离弹窗背后的页面

给弹窗背后的页面设置 element.inert:点击、焦点与辅助技术都会跳过,关闭弹窗时恢复交互,替代手工维护的焦点陷阱。

阅读英文原文

实现说明

用 inert 隔离弹窗背后的页面可以归结为函数 openInvite、closeInvite。

使用要点

  • 这是浏览器侧代码——document 在 Node 里解析不到。
  • 每一步打印都带着自己的标签:app interactive on load:。

常见问题

「用 inert 隔离弹窗背后的页面」能在裸 Node.js 里跑吗?

不能——它用到 document。这些 API 只在浏览器里有效,裸 Node 进程没有这些能力,请放到页面(或 DevTools 控制台)里执行。

主签名形如 function openInvite()

核心语句

modal?.addEventListener('close', closeInvite);
modal.querySelector('input')?.focus(); // focus lands inside the dialog
}

代码示例

// inert removes a subtree from tab order, pointer targeting, and the
// accessibility tree — the correct way to neutralize a page behind a modal.
const app = document.querySelector('#app-shell');
const modal = document.querySelector('#invite-dialog');

function openInvite() {
  app.inert = true;              // clicks, focus, and AT skip the background
  modal.inert = false;
  modal.querySelector('input')?.focus(); // focus lands inside the dialog
}

function closeInvite() {
  app.inert = false;
  modal.inert = true;
}

modal?.addEventListener('close', closeInvite);
console.log('app interactive on load:', app.inert === false);