javascript技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript技巧 > js document对象属性

JavaScript中Document对象常见的的属性分析实例详解

作者:长城2024

JavaScript中的Document对象是网页开发的核心接口,为开发者提供了操作HTML文档的桥梁,它包含丰富的属性和方法,本文给大家介绍JavaScript中Document对象常见的的属性分析,感兴趣的朋友跟随小编一起看看吧

         JavaScript中的Document对象是网页开发的核心接口,作为DOM(文档对象模型)的根节点,它为开发者提供了操作HTML文档的桥梁。通过Document对象,可以访问和修改页面的结构、内容与样式,例如利用document.getElementByIddocument.querySelector获取元素,通过document.titledocument.cookie读写文档信息,实现动态更新、表单验证、用户交互响应等功能。其丰富的属性不仅涵盖了文档的基本元数据,如URL、标题、字符集、加载状态等,还提供了对页面元素集合的直接访问,如formsimageslinks等,极大提升了开发效率和代码的可操作性。在现代前端开发中,Document对象是实现动态网页和单页应用(SPA)不可或缺的基础,几乎所有与页面交互的JavaScript逻辑都依赖于它。

        随着Web标准的演进,Document对象也在不断扩展和完善。W3C和WHATWG持续推动DOM规范的发展,使其支持更多现代Web特性,如Shadow DOM、MutationObserver等,增强了对复杂应用状态的监听与控制能力。未来,Document对象将更加注重性能优化、安全性和跨平台兼容性,例如通过更高效的查询方法、更精细的权限控制来提升用户体验。同时,在Web Components、渐进式Web应用(PWA)等新兴技术中,Document对象将继续扮演关键角色,成为连接JavaScript与网页内容的核心枢纽。

        下面,对JavaScript中Document对象常见的属性进行逐一分析讲解:

第一部分:文档元数据与位置 (1-5)

1、document.title

console.log(document.title); // 输出:当前页面的标签名
document.title = "欢迎光临我的网站"; // 浏览器标签页上的文字立刻改变

2、document.URL

// 假设当前地址是 https://example.com/page?id=1#section
console.log(document.URL); // 输出:https://example.com/page?id=1#section
// document.URL = “新地址”; // 这样做是无效的,它不可写

3、document.domain

console.log(document.domain); // 假设输出:'www.example.com'
// 如果要与子域 api.example.com 通信,可以设置:
// document.domain = 'example.com';

4、document.referrer

// 如果你从 google.com 搜索后点击链接进来
console.log(document.referrer); // 输出:'https://www.google.com/'

5、document.cookie

console.log(document.cookie); // 输出:'username=John; theme=dark'
// 设置一个新 cookie
document.cookie = “language=zh-CN; path=/”;

第二部分:文档元素集合 (6-12)

6、document.body

document.body.style.backgroundColor = 'lightblue'; // 让页面背景变蓝

7、document.head

console.log(document.head.innerHTML); // 查看 head 里有什么

8、document.forms

let firstForm = document.forms[0]; // 获取第一个表单
let loginForm = document.forms['loginForm']; // 获取 name=“loginForm” 的表单

9、document.images

console.log(document.images.length); // 输出页面中图片的总数
for (let img of document.images) {
    console.log(img.src);
}

10、document.links

document.links[0].href = 'https://newsite.com'; // 修改第一个链接的地址

11、document.anchors

// 如果有一个 <a name=“section1”></a>
console.log(document.anchors[‘section1']); // 可以获取到

12、document.scripts

console.log('页面加载了 ' + document.scripts.length + ' 个 JS 文件');

第三部分:文档结构与视图 (13-17)

13、document.doctype

console.log(document.doctype.name); // 输出:'html' (如果是 HTML5 标准)

14、document.documentElement

let fullPageHeight = document.documentElement.scrollHeight; // 获取整个文档滚动高度

15、document.defaultView

let isChrome = document.defaultView.navigator.userAgent.includes('Chrome');

16、document.activeElement

if (document.activeElement.id === 'username') {
    console.log('用户正在输入用户名');
}

17、document.baseURI

// 如果页面有 <base href=“https://example.com/newbase/”>
console.log(document.baseURI); // 输出:'https://example.com/newbase/'

第四部分:编码与状态 (18-20)

18、document.charset / 19、document.characterSet

console.log(document.characterSet); // 输出:'UTF-8'

20、document.readyState

if (document.readyState === 'complete') {
    console.log('页面完全加载好了');
}

第五部分:文件信息与遗留属性 (21-29)

注意:fileCreatedDate, fileModifiedDate, fileSize 这些属性是非标准的,主要出现在旧版 IE 中,现代浏览器不支持或返回空值。

21、document.lastModified

console.log('本页面最后更新于:' + document.lastModified);

22、document.fileCreatedDate(非标准/IE)

23、document.fileModifiedDate(非标准/IE)

24、document.fileSize(非标准/IE)

25、document.bgColor

document.bgColor = “yellow”; // 不推荐使用

26、document.fgColor

27、document.linkColor

28、document.alinkColor

29、document.vlinkColor

第六部分:集合与扩展 (30-32)

30、document.all

// 获取页面上第 5 个元素
let element = document.all[4];
// 检测 IE 的古老写法(现在不推荐)
if (document.all) {
    // 如果是 IE
}

31、document.expando

// 在旧版 IE 中
document.expando = false;
document.body.myCustomProp = “test”; // 这将会失败

32、document.location

console.log(document.location.hostname); // 输出当前域名
// 3 秒后跳转到百度
setTimeout(() => {
    document.location = 'https://www.baidu.com';
}, 3000);

第七部分:节点导航与关系属性 (33-40)

33、document.firstChild

console.log(document.firstChild.nodeName); // 可能输出 '#comment' 或 'html' 或 '#text'

34、document.lastChild

console.log(document.lastChild.nodeName); // 通常输出 'HTML'

35、document.childNodes

for (let node of document.childNodes) {
    console.log(node.nodeType, node.nodeName); // 输出:10 'html' 之类的信息
}

36、document.firstElementChild

console.log(document.firstElementChild.tagName); // 输出:'HTML'

37、document.lastElementChild

console.log(document.lastElementChild === document.documentElement); // true

38、document.children

console.log(document.children.length); // 通常是 1
console.log(document.children[0].tagName); // 输出:'HTML'

39、document.nodeName

console.log(document.nodeName); // 输出:'#document'

40、document.nodeType

console.log(document.nodeType); // 输出:9

第八部分:文档事件与处理程序 (41-46)

41、document.onload

document.onload = function() {
    console.log('文档加载完成');
};

42、document.onreadystatechange

document.onreadystatechange = function() {
    if (document.readyState === 'interactive') {
        console.log('DOM 解析完成,但资源还在加载');
    }
    if (document.readyState === 'complete') {
        console.log('页面完全加载完成');
    }
};

43、document.onscroll

document.onscroll = function() {
    console.log('滚动位置:' + window.scrollY);
};

44、document.onclick

document.onclick = function(e) {
    console.log('点击了:' + e.target.tagName);
    console.log('坐标:' + e.clientX + ', ' + e.clientY);
};

45、document.onkeydown

document.onkeydown = function(e) {
    if (e.key === 'Escape') {
        console.log('按下了 ESC 键');
        closeModal(); // 假设有一个关闭弹窗的函数
    }
};

46、document.oncopy

document.oncopy = function(e) {
    alert('内容已复制!');
    // 修改复制的内容
    e.clipboardData.setData('text/plain', '复制的内容被修改了');
    e.preventDefault(); // 阻止默认复制行为
};

第九部分:文档兼容性与视图 (47-53)

47、document.compatMode

if (document.compatMode === 'CSS1Compat') {
    console.log('标准模式渲染');
} else {
    console.log('怪异模式渲染');
}

48、document.documentURI

console.log(document.documentURI); // 输出当前 URL

49、document.inputEncoding

// 现代浏览器请使用 document.characterSet
console.log(document.characterSet);

50、document.hidden

document.addEventListener('visibilitychange', function() {
    if (document.hidden) {
        console.log('用户切换到了其他标签页');
        pauseVideo(); // 暂停视频播放
    } else {
        console.log('用户回来了');
        playVideo(); // 恢复播放
    }
});

51、document.visibilityState

if (document.visibilityState === 'visible') {
    console.log('页面可见,可以执行动画');
}

52、document.designMode

// 开启整个页面的编辑模式
document.designMode = 'on';
// 现在用户可以直接在页面上打字修改内容

53、document.execCommand()

// 将选中文本加粗(需要先开启 designMode 或 contenteditable)
document.execCommand('bold', false, null);
// 复制选中的文本
document.execCommand('copy');
// 插入一个链接
document.execCommand('createLink', false, 'https://example.com');

第十部分:文档集合与特殊属性 (54-60)

54、document.styleSheets

console.log('页面有 ' + document.styleSheets.length + ' 个样式表');
// 查看第一个样式表的规则
let firstSheet = document.styleSheets[0];
console.log(firstSheet.cssRules); // 查看 CSS 规则

55、document.embeds

let flashCount = document.embeds.length; // 页面中 Flash 嵌入的数量

56、document.plugins

console.log(document.plugins === document.embeds); // true

57、document.fonts

document.fonts.ready.then(function() {
    console.log('所有字体加载完成');
    // 可以安全渲染文本了
});
console.log(document.fonts.status); // 字体加载状态

58、document.cookieEnabled

if (!document.cookieEnabled) {
    alert('请启用 Cookie 以获得完整体验');
}

59、document.currentScript

// 在 script.js 文件中
console.log(document.currentScript.src); // 输出当前脚本的 URL
console.log(document.currentScript.getAttribute('data-config')); // 获取自定义数据属性

60、document.fullscreenElement

function toggleFullscreen() {
    if (document.fullscreenElement) {
        document.exitFullscreen(); // 退出全屏
    } else {
        document.documentElement.requestFullscreen(); // 整个文档全屏
    }
}

总 结 列 表

        下面对上面讲解的JavaScript的 document 对象 60 个常见的属性进行总结列表。

第一部分:文档元数据与位置 (1-5)

属性含义词源语法参数及说明
1document.title获取或设置当前文档的标题。“title”意为标题。let docTitle = document.title;
document.title = "新标题";
无参数。作为 Getter 时返回字符串,作为 Setter 时需传入新标题字符串。
2document.URL返回当前文档的完整 URL 地址。“URL” 是 Uniform Resource Locator(统一资源定位符)的缩写。let url = document.URL;只读属性,无参数。返回一个包含当前页面 URL 的字符串。
3document.domain获取或设置当前文档的域名,用于同源策略下的跨子域通信。“domain”意为域名。let domain = document.domain;
document.domain = "example.com";
可作为 Getter/Setter。通常只能设置为当前域名的父域(例如从 "sub.example.com" 设为 "example.com")。
4document.referrer返回链接到当前页面的前一页面的 URL。“referrer”意为引荐人、来源页面。let referringPage = document.referrer;只读属性。如果用户直接访问该页面(如通过书签),则返回空字符串。
5document.cookie获取或设置与当前文档相关联的所有 HTTP cookie。“cookie”在此指网络浏览器的数据存储机制。let cookies = document.cookie;
document.cookie = "key=value; path=/";
读取时返回包含所有 cookie 的字符串(以分号分隔)。写入时需设置键值对及可选属性(如 pathexpires)。

第二部分:文档元素集合 (6-12)

属性含义词源语法参数及说明
6document.body返回当前文档的 <body> 元素。“body”指文档的主体部分。let bodyEl = document.body;只读属性。可以直接操作该元素,例如设置背景色。
7document.head返回当前文档的 <head> 元素。“head”指文档的头部区域。let headEl = document.head;只读属性。
8document.forms返回当前文档中所有 <form> 元素的集合(HTMLCollection)。“forms”是 form 的复数形式。let formsCollection = document.forms;只读属性。返回一个类数组对象,可以通过索引或表单的 name/id 访问。
9document.images返回当前文档中所有 <img> 元素的集合(HTMLCollection)。“images”是 image 的复数形式。let imagesCollection = document.images;只读属性。
10document.links返回当前文档中所有带有 href 属性的 <area> 元素和 <a> 元素的集合(HTMLCollection)。“links”是 link 的复数形式。let linksCollection = document.links;只读属性。
11document.anchors返回当前文档中所有带有 name 属性的 <a> 元素的集合(HTMLCollection)。“anchors”是 anchor(锚点)的复数形式。let anchorsCollection = document.anchors;只读属性。注意:现代 HTML 中通常使用 id 属性创建锚点,而非 name
12document.scripts返回当前文档中所有 <script> 元素的集合(HTMLCollection)。“scripts”是 script 的复数形式。let scriptsCollection = document.scripts;只读属性。

第三部分:文档结构与视图 (13-17)

属性含义词源语法参数及说明
13document.doctype返回当前文档关联的文档类型声明(DTD)。“doctype”是 Document Type Declaration 的简称。let doctype = document.doctype;只读属性。返回一个 DocumentType 对象,如果没有则返回 null
14document.documentElement返回文档的根元素(对于 HTML 文档,即 <html> 元素)。“documentElement”意为文档元素。let rootEl = document.documentElement;只读属性。这是获取根元素的标准方法。
15document.defaultView返回与当前文档关联的 window 对象。“defaultView”意为默认视图。let win = document.defaultView;只读属性。在浏览器中,通常等同于 window
16document.activeElement返回当前文档中获得焦点的元素。“activeElement”意为激活中的元素。let activeEl = document.activeElement;只读属性。如果没有元素获得焦点,则返回 <body> 元素或 null
17document.baseURI返回文档的绝对基础 URI,通常用于解析相对路径。“baseURI”是 Base Uniform Resource Identifier 的缩写。let baseUri = document.baseURI;只读属性。通常由 <base> 标签设置,否则默认为文档地址。

第四部分:编码与状态 (18-20)

属性含义词源语法参数及说明
18/19document.charset / document.characterSet返回文档使用的字符编码。“charset”是 Character Set 的缩写。let encoding = document.characterSet;只读属性。charset 是 characterSet 的别名,推荐使用后者。
20document.readyState返回当前文档的加载状态。“readyState”意为就绪状态。let state = document.readyState;只读属性。返回值有三种:loading(加载中)、interactive(DOM 解析完成)、complete(页面完全加载)。

第五部分:文件信息与遗留属性 (21-29)

属性含义词源语法参数及说明
21document.lastModified返回文档最后被修改的日期和时间(字符串形式)。“lastModified”意为最后修改时间。let modified = document.lastModified;只读属性。返回一个字符串,格式因服务器而异。
22-24document.fileCreatedDate / fileModifiedDate / fileSize(非标准,仅旧版 IE)分别表示文件的创建日期、修改日期和大小。-不建议使用。在现代浏览器中无效。无。
25document.bgColor获取或设置文档的背景颜色。“bgColor”是 Background Color 的缩写。document.bgColor = "red";已废弃,应使用 CSS 的 document.body.style.backgroundColor 替代。
26document.fgColor获取或设置文档的前景色(文本颜色)。“fgColor”是 Foreground Color 的缩写。document.fgColor = "black";已废弃,应使用 CSS 替代。
27-29document.linkColor / alinkColor / vlinkColor分别设置或获取链接、激活链接、已访问链接的颜色。“link”链接,“a”指 anchor,“v”指 visited。document.linkColor = "blue";已废弃,应使用 CSS 伪类(:link:active:visited)替代。

第六部分:集合与扩展 (30-32)

属性含义词源语法参数及说明
30document.all返回一个包含文档中所有元素的 HTMLAllCollection(非标准,仅 IE 支持)。“all”意为全部。let allEl = document.all;只读属性。非标准,不应在现代 Web 开发中使用。
31document.expando允许在 IE 中控制是否允许扩展文档的属性(非标准,仅 IE)。“expando”意为扩展属性。document.expando = false;非标准,仅 IE。用于性能优化,现已无用。
32document.location返回一个 Location 对象,包含文档 URL 的信息,并可用来导航。“location”意为位置。let loc = document.location;
document.location.href = "newpage.html";
既是只读属性(返回对象),也是可写属性(赋值字符串可导航到新页面)。与 window.location 基本相同。

第七部分:节点导航与关系属性 (33-40)

属性含义词源语法参数及说明
33document.firstChild返回文档的第一个子节点。“firstChild”意为第一个子节点。let first = document.firstChild;只读属性。注意:在 HTML 中,根节点 document 的第一个子节点通常是 <!DOCTYPE> 声明,但可能因空白节点而异。
34document.lastChild返回文档的最后一个子节点。“lastChild”意为最后一个子节点。let last = document.lastChild;只读属性。通常返回 <html> 元素。
35document.childNodes返回文档所有子节点的 NodeList 集合。“childNodes”意为子节点们。let children = document.childNodes;只读属性。通常包含 doctype 和 html 元素。
36document.firstElementChild返回文档的第一个子元素节点(忽略文本和注释节点)。“firstElementChild”意为第一个元素子节点。let firstEl = document.firstElementChild;只读属性。对于 HTML 文档,通常是 <html> 元素。
37document.lastElementChild返回文档的最后一个子元素节点。“lastElementChild”意为最后一个元素子节点。let lastEl = document.lastElementChild;只读属性。通常也是 <html> 元素。
38document.children返回文档所有子元素节点的 HTMLCollection 集合。“children”意为孩子们。let elChildren = document.children;只读属性。通常只包含 <html> 元素。
39document.nodeName返回文档节点的名称。“nodeName”意为节点名称。let name = document.nodeName;只读属性。对于 Document 节点,总是返回 #document
40document.nodeType返回文档节点的类型。“nodeType”意为节点类型。let type = document.nodeType;只读属性。Document 节点的类型常量是 9。

第八部分:文档事件与处理程序 (41-46)

属性含义词源语法参数及说明
41document.onload页面加载完成时的事件处理程序(通常应使用 window.onload)。“onload”意为当加载时。document.onload = function() { ... };此事件通常在 <body> 或 <frameset> 上触发。更推荐使用 window.addEventListener('load', ...)
42document.onreadystatechange当 document.readyState 属性发生变化时触发的事件处理程序。“onreadystatechange”意为当就绪状态改变时。document.onreadystatechange = function() { ... };用于监听文档加载过程。
43document.onscroll当文档滚动条滚动时触发的事件处理程序。“onscroll”意为当滚动时。document.onscroll = function() { ... };注意:滚动事件也可能发生在其他元素上。
44document.onclick当文档被点击时触发的事件处理程序。“onclick”意为当点击时。document.onclick = function(event) { ... };通过事件对象 event 可以获取点击位置、目标元素等。
45document.onkeydown当按键被按下时触发的事件处理程序。“onkeydown”意为当键按下时。document.onkeydown = function(event) { ... };常用于实现键盘快捷键。
46document.oncopy当用户复制元素内容时触发的事件处理程序。“oncopy”意为当复制时。document.oncopy = function(event) { ... };可以用于修改复制的内容或阻止复制。

第九部分:文档兼容性与视图 (47-53)

属性含义词源语法参数及说明
47document.compatMode返回文档的渲染模式是怪异模式还是标准模式。“compatMode”是 Compatibility Mode(兼容模式)的缩写。let mode = document.compatMode;只读属性。返回 "CSS1Compat"(标准模式)或 "BackCompat"(怪异模式)。
48document.documentURI返回文档的位置(URI)。“documentURI”是 Document Uniform Resource Identifier 的缩写。let uri = document.documentURI;只读属性。与 document.URL 类似,但 documentURI 对所有文档(包括 XML)都可用,且不可变。
49document.inputEncoding返回文档的字符编码。“inputEncoding”意为输入编码。let encoding = document.inputEncoding;只读属性。已废弃,应使用 document.characterSet
50document.hidden返回一个布尔值,表示页面是否被认为隐藏。“hidden”意为隐藏的。let isHidden = document.hidden;只读属性。是 Page Visibility API 的一部分。
51document.visibilityState返回文档的可见性状态。“visibilityState”意为可见性状态。let state = document.visibilityState;只读属性。返回值:'visible'(页面可见)、'hidden'(页面隐藏)、'prerender'(预渲染)。
52document.designMode控制整个文档是否可编辑。“designMode”意为设计模式。document.designMode = "on";
document.designMode = "off";
设置为 "on" 时,整个文档区域变为可编辑状态(类似富文本编辑器)。
53document.execCommand()在可编辑内容区域执行一个命令(如加粗、创建链接)。“execCommand”意为执行命令。document.execCommand('bold', false, null);参数:命令名、是否显示用户界面(通常为 false)、命令所需的值。

第十部分:文档集合与特殊属性 (54-60)

属性含义词源语法参数及说明
54document.styleSheets返回一个包含所有显式链接或嵌入到文档中的样式表对象的 StyleSheetList。“styleSheets”意为样式表们。let sheets = document.styleSheets;只读属性。可以用于动态操作 CSS 规则。
55document.embeds返回当前文档中所有 <embed> 元素的集合(HTMLCollection)。“embeds”是 embed 的复数形式。let embedsCollection = document.embeds;只读属性。用于获取页面中嵌入的插件内容。
56document.plugins返回一个包含所有已安装插件的 PluginArray。“plugins”是 plugin 的复数形式。let plugins = document.plugins;只读属性。通常用于检测特定插件是否存在(如 Flash)。
57document.fonts返回文档的 FontFaceSet 接口,用于检测和加载字体。“fonts”意为字体们。let fontSet = document.fonts;只读属性。是 CSS Font Loading API 的一部分。
58document.cookieEnabled返回一个布尔值,指示浏览器是否启用了 cookie。“cookieEnabled”意为 Cookie 已启用。let enabled = document.cookieEnabled;只读属性。用于检测用户的 Cookie 设置。
59document.currentScript返回当前正在执行的 <script> 元素。“currentScript”意为当前脚本。let curScript = document.currentScript;只读属性。对于内联脚本和外部脚本都有效,用于获取脚本自身的元数据。
60document.fullscreenElement返回当前正在以全屏模式显示的元素。“fullscreenElement”意为全屏元素。let fsEl = document.fullscreenElement;只读属性。如果没有元素处于全屏状态,则返回 null。

到此这篇关于JavaScript中Document对象常见的的属性分析的文章就介绍到这了,更多相关js document对象属性内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文