← 中文资源

简体中文版本

hidden 把元素从渲染与焦点中移除

hidden 让元素停止渲染、无法聚焦,但仍留在 DOM 里可被查询;作者样式里更强的 display 规则会盖过它,需要补一条 [hidden] 规则恢复保证。

阅读英文原文

实现说明

顶层就这几处状态:box、ghost、style、fix。

使用要点

  • 这是浏览器侧代码——document 在 Node 里解析不到。
  • 跑完文件,输出里会留下标记——display none:、not rendered:、still queryable:。

常见问题

「hidden 把元素从渲染与焦点中移除」能在裸 Node.js 里跑吗?

不能——这类 API 归浏览器环境所有(document),Node 里不存在。请在页面或 DevTools 控制台中运行。

核心语句

style.textContent = 'button { display: grid; }';
fix.textContent = '[hidden] { display: none; }';
const ghost = document.createElement('button');

代码示例

const box = document.createElement('div');
box.textContent = 'content';
document.body.append(box);

const ghost = document.createElement('button');
ghost.textContent = 'ghost';
box.append(ghost);
ghost.hidden = true;

// Rendering is off, but the element remains in the DOM and queryable
console.log('display none:', getComputedStyle(ghost).display === 'none');
console.log('not rendered:', ghost.offsetParent === null);
console.log('still queryable:', box.querySelector('button') === ghost);

// Hidden elements cannot take focus either
ghost.focus();
console.log('focus refused:', document.activeElement !== ghost);

// A stronger author rule beats the UA's [hidden] { display: none } —
// the classic way to accidentally un-hide something
const style = document.createElement('style');
style.textContent = 'button { display: grid; }';
document.head.append(style);
console.log('author rule overrides hidden:', getComputedStyle(ghost).display === 'grid');

// The documented fix: ship an attribute selector in your own stylesheet
const fix = document.createElement('style');
fix.textContent = '[hidden] { display: none; }';
document.head.append(fix);
console.log('fixed with [hidden] rule:', getComputedStyle(ghost).display === 'none');