JavaScript 窗口(window)和文档(document)有什么区别

JavaScript 窗口(window)和文档(document)有什么区别

什么是JavaScript窗口?

窗口是JavaScript对象层次结构中的根/顶级对象。它是JavaScript中的全局/根对象,并且是文档对象模型(DOM)的根对象。

什么是JavaScript文档?

文档是位于窗口对象内部的对象,我们使用文档对象来操作文档内部的内容。

首先加载到浏览器中的是窗口,与该窗口相关的属性存储在窗口对象中。与窗口对象相关的属性包括length,innerWidth,innerHeight,caches等。

那么,文档对象是什么呢?

在窗口加载后,窗口内加载了一个文档(如HTML、PHP或其他文档),与该文档相关的属性存储在文档对象中。与文档对象相关的属性包括title,URL,cookie等。

语法:

  • window对象:
window.propertyname;
  • document对象:
document.propertyname
// OR
window.document.propertyname

示例1: 集中注意力在窗口对象上。

JavaScript

<!DOCTYPE html> 
<html lang="en"> 
  
<head> 
    <meta charset="UTF-8"> 
    <meta http-equiv="X-UA-Compatible" content="IE=edge"> 
    <meta name="viewport" 
        content="width=device-width, initial-scale=1.0"> 
    <title>Document</title> 
</head> 
  
<body> 
    <h1></h1> 
    <p id="innerheight"></p> 
  
    <p id="innerwidth"></p> 
  
    <script> 
        window.document.bgColor = "aqua"; 
        const height = document.getElementById('innerheight'); 
        const width = document.getElementById('innerwidth'); 
        window.document.querySelector('h1').textContent =  
            "Welcome to window object"; 
        height.textContent = "innerheight - " +  
            window.innerHeight; 
        width.textContent = "innerwidth - " +  
            window.innerWidth; 
    </script> 
</body> 
  
</html>

输出:

JavaScript 窗口(window)和文档(document)有什么区别

示例2: 专注于文档对象。

HTML

<!DOCTYPE html> 
<html lang="en"> 
  
<head> 
    <meta charset="UTF-8"> 
    <meta http-equiv="X-UA-Compatible" content="IE=edge"> 
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0"> 
    <title>Document object</title> 
</head> 
  
<body style="color:white"> 
    <h1></h1> 
    <p class="details"></p> 
  
    <p class="details"></p> 
  
    <p class="details"></p> 
  
    <script> 
        document.bgColor = "rgb(89, 135, 235)"; 
        const text = prompt('enter the text to appear on screen'); 
        const h1 = document.querySelector('h1'); 
        h1.textContent = text; 
        const p = document.getElementsByClassName('details'); 
        p[0].textContent = "document type:" +  
              document.contentType; 
        p[1].textContent = "url :" + document.bgColor; 
        p[2].textContent = "title :" + document.title; 
    </script> 
</body> 
  
</html>

输出结果:

JavaScript 窗口(window)和文档(document)有什么区别

document window
它表示加载在窗口或浏览器内部的文档。 它表示您正在查看内容的浏览器窗口。
与文档相关的属性存储在文档对象中。 与窗口相关的属性存储在窗口对象中。
它在加载窗口之后加载,因为窗口包含一个文档。 它在文档之前加载,因为窗口容器文档。
它是文档对象模型的根元素。 窗口是所有对象、函数等的全局元素。
它是窗口的对象。 它是浏览器的对象。
我们无法在文档内部访问窗口对象的属性。 我们可以在窗口内部访问文档对象的属性。
逻辑上: document:{ properties} 逻辑上: window:{ document:{properties} }
示例:document.title将返回文档的标题 示例:window.document.title将返回文档的标题。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程