我如何引用<HTML>元素's对应的DOM对象

How can I reference the <HTML> element's corresponding DOM object?

本文关键字:元素 对象 DOM gt HTML 引用 lt 何引用      更新时间:2023-09-26

这就是访问<body>元素以设置背景样式的方法:

document.body.style.background = '';

但是,我怎样才能以类似的方式访问<html>元素呢?以下不起作用:

document.html.style.background = '';

<html>元素可以通过document.documentElement属性引用。通常,任何文档的根元素都可以通过.documentElement引用。

document.documentElement.style.background = '';

注意:.style.backgroundbackground的值作为内联样式属性返回。也就是说,使用<html style="background:..">定义。如果要获得计算样式属性,请使用getComputedStyle:

var style = window.getComputedStyle(document.documentElement);
var bgColor = style.backgroundColor;

根元素(<html>)可以在document.documentElement中找到,而不是在document.html中找到。

这是因为documentElement是标准DOM,而不是HTML特定的扩展。

为什么也要在HTML上设置样式,对任何样式都要使用body标记。。

要更改应用于html的背景,您必须访问页面的根

使用document.dococumentElement可以进行

使用此

document.documentElement.style.background = '';