当前位置: 首页 > web >正文

document.documentElement详解

核心概念

  1. 定义

    • 它始终指向当前文档的根元素,在 HTML 文档中对应 <html> 标签。
    • document.body(对应 <body>)和 document.head(对应 <head>)形成层级关系。
  2. document.body 的区别

    <html> <!-- document.documentElement --><head> <!-- document.head --></head><body> <!-- document.body --></body>
    </html>
    

常见用途

1. 操作根元素样式
// 修改根元素背景色
document.documentElement.style.backgroundColor = "#f0f0f0";// 添加 CSS 类名
document.documentElement.classList.add("dark-mode");
2. 获取文档尺寸
// 获取视口宽度(兼容性写法)
const width = document.documentElement.clientWidth;// 获取整个文档高度(包括滚动区域)
const height = document.documentElement.scrollHeight;
3. 动态主题切换
// 通过 CSS 变量定义主题
document.documentElement.style.setProperty("--primary-color", "#ff5722");

注意事项

  1. 兼容性

    • 现代浏览器均支持,但在旧版 IE 中需注意:
      • IE6-8 使用 document.documentElement 获取视口尺寸。
      • 其他浏览器可能使用 document.body
  2. XML 文档

    • 在非 HTML 文档(如 XML)中,document.documentElement 指向 XML 的根元素。
  3. window.document 的区别

    • window.document 是文档对象,而 document.documentElement 是具体的 DOM 元素。

代码示例

// 获取根元素
const rootElement = document.documentElement;// 修改根元素属性
rootElement.setAttribute("lang", "en");// 监听根元素尺寸变化(需配合 ResizeObserver)
const observer = new ResizeObserver(entries => {console.log("文档尺寸变化:", entries[0].contentRect);
});
observer.observe(rootElement);

总结

  • 核心作用:直接操作 HTML 根元素,控制全局样式或获取文档级信息。
  • 典型场景:主题切换、响应式布局、动态样式注入。
  • 替代方案:部分操作可用 document.querySelector("html") 实现,但 document.documentElement 更高效。
http://www.xdnf.cn/news/15532.html

相关文章:

  • LVS的集群技术和分布式
  • HTTP 四种常见方法
  • 飞桨AI Studio云编程环境搭建
  • redis实现红锁
  • MCP终极篇!MCP Web Chat项目实战分享
  • 【牛客刷题】小红的数字删除
  • 算法:投票法
  • VUE export import
  • MinIo快速入门
  • JJ20 Final Lap演唱会纪念票根生成工具
  • MIPI DSI (一) MIPI DSI 联盟概述
  • Oracle 学习笔记
  • Docker入门基础
  • GaussDB between的用法
  • 文心一言 4.5 开源深度剖析:中文霸主登场,开源引擎重塑大模型生态
  • 用基础模型构建应用(第九章)AI Engineering: Building Applications with Foundation Models学习笔记
  • # 检测 COM 服务器在线状态
  • python 双下划线开头函数
  • 网络协议和基础通信原理
  • Go泛型完全指南:从基础到实战应用
  • Fluent许可文件安装和配置
  • 车载诊断框架 --- 车载诊断GuideLine
  • 如何集成光栅传感器到FPGA+ARM系统中?
  • 如何更改Blender插件安装位置呢?
  • qt 使用memcpy进行内存拷贝时注意的问题
  • 硬盘爆满不够用?这个免费神器帮你找回50GB硬盘空间
  • EasyExcel实现Excel文件导入导出
  • [Nagios Core] 事件调度 | 检查执行 | 插件与进程
  • 解决Qt中“known incorrect sRGB profile“警告的Photoshop修改方法
  • 如何基于FFMPEG 实现视频推拉流