Home  >  Article  >  Web Front-end  >  Detailed explanation of BOM and DOM definitions and usage examples in JavaScript

Detailed explanation of BOM and DOM definitions and usage examples in JavaScript

伊谢尔伦
伊谢尔伦Original
2017-07-18 16:05:231568browse

DOM is a platform- and language-neutral interface that enables programs and scripts to dynamically access and update the content, structure, and style of a document. , and the BOM defines the interface of each functional component of the browser that JavaScript can operate.

DOM (Document Object Model) is the application programming interface (API) for HTML and XML.

The BOM mainly deals with browser windows and frames, but usually browser-specific JavaScript extensions are considered part of the BOM. These extensions include:

弹出新的浏览器窗口
移动、关闭浏览器窗口以及调整窗口大小
提供 Web 浏览器详细信息的定位对象
提供用户屏幕分辨率详细信息的屏幕对象
对 cookie 的支持
IE 扩展了 BOM,加入了 ActiveXObject 类,可以通过 JavaScript 实例化 ActiveX 对象

<span style="font-family:NSimsun">javacsript</span> is accessed and controlled by accessing the <span style="font-family:NSimsun">BOM</span> (Browser Object Model) object , modify the client (browser), because <span style="font-family:NSimsun">BOM</span>’s <span style="font-family:NSimsun">window</span> contains <span style="font-family:NSimsun">document</span>, the properties and methods of the window object are directly available and perceived, so you can directly use the <span style="font-family:NSimsun">document</span> of the <span style="font-family:NSimsun">window</span> object Attributes, through the <span style="font-family:NSimsun">document</span> attributes, you can access, retrieve, and modify the content and structure of the XHTML document. Because the <span style="font-family:NSimsun">document</span> object is the root node of the DOM (Document Object Model) model. It can be said that BOM contains <span style="font-family:NSimsun">DOM</span> (object). What the browser provides for access is the BOM object, and then accesses <span style="font-family:NSimsun">DOM</span> from the BOM object. Object, so that js can operate the browser and the documents read by the browser. Among them,
DOM contains: <span style="font-family:NSimsun">window</span>

Window对象包含属性:document、location、navigator、screen、history、frames
Document根节点包含子节点:forms、location、anchors、images、links

As can be seen from <span style="font-family:NSimsun">window.document</span>, the DOM The most fundamental object is the sub-object of the window object of the BOM.

Difference: DOM describes the methods and interfaces for processing web page content, and BOM describes the methods and interfaces for interacting with the browser.

Understanding DOM

Let’s take a look at the following code first:

  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  <head>
      <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
      <title>DOM</title>
  </head>
  <body>
      <h2><a href="http://www.baidu.com">javascript DOM</a></h2>
      <p>对HTML元素进行操作,可添加、改变或移除css样式等</p>
      <ul>
          <li>Javascript</li>
          <li>DOM</li>
          <li>CSS</li>
      </ul>
  </body>
  </html>

Decompose the HTML code into a DOM node hierarchy diagram:


 **HTML文档可以说由节点构成的集合,DOM节点有:**
1. 元素节点:上图中<html>、<body>、<p>等都是元素节点,即标签。
2. 文本节点:向用户展示的内容,如<li>...</li>中的JavaScript、DOM、CSS等文本。
3. 属性节点:元素属性,如<a>标签的链接属性href="http://www.baidu.com"。

Node attribute node attribute nodeName returns a string whose content is the name of the node nodeType returns an integer, this value represents the type of the given node nodeValue returns The current value of the given node

Traverse the node tree Traverse the node tree childNodes Returns an array consisting of the child nodes of the given element firstChild returns the first child node lastChild returns the last child node parentNode returns a given The parent node of a given node nextSibling returns the next child node of the given node previousSibling returns the previous child node of the given node

DOM operation DOM operation creatElement(element) creates a new element node creatTextNode() creates a A new text node containing the given text appendChild() Adds a new subsection after the last node list of the specified node insertBefore() Inserts a given node before the given child node of a given element node removeChild() From Delete a child node from a given element. replaceChild() replaces a child node in a given parent element with another node.

DOM represents the document by creating a tree and describes the methods and interfaces for processing web page content. , thus giving developers unprecedented control over the content and structure of the document, and nodes can be easily deleted, added and replaced using the DOM API.

1. Access Node

`var oHtml = document.documentElement;` //返回存在于 XML 以及 HTML 文档中的文档根节点,oHtml包含了一个表示<html />的HTMLElement对象
`document.body` //是对 HTML 页面的特殊扩展,提供了对 <body> 标签的直接访问</span><span></span></span>
`document.getElementById("ID")` //通过指定的 ID 来返回元素,getElementById() 无法工作在 XML 中,IE6还会返回name为指定ID的元素
`document.getElementByName("name")`//获取所有name特性等于指定值的元素,不过在IE6和Opera7.5上还会返回id为给定名称的元素且仅检查<input/>和<img/>
`var x=document.getElementsByTagName("p");` //使用指定的标签名返回所有的元素列表NodeList,索引号从0开始。当参数是一个星号的时候,IE6并不返回所有的元素,必须用document.all来替代

2. Characteristics and methods of Node node

firstChild //Node,指向在childNodes列表中的第一个节点 
lastChild //Node,指向在childNodes列表中的最后一个节点 
parentNode //Node,指向父节
ownerDocument //Document,指向这个节点所属的文档 
firstChild //Node,指向在childNodes列表中的第一个节点  
lastChild //Node,指向在childNodes列表中的最后一个节点  
parentNode //Node,指向父节点  
childNodes //NodeList,所有子节点的列表 
previousSibling /Node,/指向前一个兄弟节点:如果这个节点就是第一个节点,那么该值为 null 
`nextSibling` //Node,指向后一个兄弟节点:如果这个节点就是最后一个节点,那么该值为null 
`hasChildNodes()` //Boolean,当childNodes包含一个或多个节点时,返回真值

3.DOM events

  DOM同时两种事件模型:冒泡型事件和捕获型事件 
  冒泡型事件:事件按照从最特定的事件目标到最不特定的事件目标的顺序触发 
  <body onclick="handleClick()"> 
    <p onclick="handleClick()">Click Me</p> 
  </body> 
  触发的顺序是:p、body、html(IE 6.0和Mozilla 1.0)、document、window(Mozilla 1.0) 

  捕获型事件:与冒泡事件相反的过程,事件从最不精确的对象开始触发,然后到最精确 
  上面例子触发的顺序是:document、p 
  DOM事件模型最独特的性质是,文本节点也触发事件(在IE中不会)。

4.Event handling function/listening Function

 **事件处理函数/监听函数** 
在JavaScript中: 
var op = document.getElementById("p1"); 
op.onclick = function(){ //onclick只能用小写,默认为冒泡型事件 
  alert("Clicked!"); 
} 

在HTML中: 
<p onclick="javascript: alert("Clicked!")"></p> //onclick大小写任意

IE event handler attachEvent() and detachEvent()

In IE, each element and window object has two methods: <span style="font-family:NSimsun">attachEvent() and detachEvent()</span>, these two methods accept the same two parameters, the event handler name and the event handler function, such as:

[object].attachEvent("name_of_event_handler","function_to_attach") 
[object].detachEvent("name_of_event_handler","function_to_remove") 
var fnClick = function(){ 
  alert("Clicked!"); 
} 
op.attachEvent("onclick", fnClick); //添加事件处理函数 
op.attachEvent("onclick", fnClickAnother); // 可以添加多个事件处理函数 
op.detachEvent("onclick", fnClick); //移除事件处理函数

When using <span style="font-family:NSimsun">attachEvent ()</span> method, the event handler will run in the global scope, so this is equal to window.

Cross-browser event handler

addHandler()和removeHandler()

<span style="font-family:NSimsun">addHandler()</span>The method belongs to an object called EventUntil(). Both methods are Accepts the same three parameters, the element to operate on, the event name and the event handler function.

DOM level 0 event handler

DOM level 0 event handler: Assign a function to the handler attribute of an event

<input type="button" value="按钮2" id="ben2"/>
     var btn2=document.getElementById(&#39;btn2&#39;);获得btn2按钮对象
     btn2.onclick      //给btn2添加onclick属性,属性又触发了一个事件处理程序

btn2.onclick=function(){
}                    //添加匿名函数

btn2.onclick=null      //删除onclick属性

BOM part

<span style="font-family:NSimsun">BOM</span>的核心是<span style="font-family:NSimsun">window</span>,而<span style="font-family:NSimsun">window</span>对象又具有双重角色,它既是通过js访问浏览器窗口的一个接口,又是一个<span style="font-family:NSimsun">Global</span>(全局)对象。这意味着在网页中定义的任何对象,变量和函数,都以window作为其<span style="font-family:NSimsun">global</span>对象。

window.close(); //关闭窗口 

window.alert("message"); //弹出一个具有OK按钮的系统消息框,显示指定的文本 

window.confirm("Are you sure?"); //弹出一个具有OK和Cancel按钮的询问对话框,返回一个布尔值 

window.prompt("What&#39;s your name?", "Default"); //提示用户输入信息,接受两个参数,即要显示给用户的文本和文本框中的默认值,将文本框中的值作为函数值返回 

window.status //可以使状态栏的文本暂时改变 

window.defaultStatus //默认的状态栏信息,可在用户离开当前页面前一直改变文本 

window.setTimeout("alert(&#39;xxx&#39;)", 1000); //设置在指定的毫秒数后执行指定的代码,接受2个参数,要执行的代码和等待的毫秒数 

window.clearTimeout("ID"); //取消还未执行的暂停,将暂停ID传递给它 

window.setInterval(function, 1000); //无限次地每隔指定的时间段重复一次指定的代码,参数同setTimeout()一样 

window.clearInterval("ID"); //取消时间间隔,将间隔ID传递给它 

window.history.go(-1); //访问浏览器窗口的历史,负数为后退,正数为前进 

window.history.back(); //同上 

window.history.forward(); //同上 

window.history.length //可以查看历史中的页面数

document对象

document对象:实际上是window对象的属性,document == window.document为true,是唯一一个既属于BOM又属于DOM的对象 

document.lastModified //获取最后一次修改页面的日期的字符串表示 

document.referrer //用于跟踪用户从哪里链接过来的 

document.title //获取当前页面的标题,可读写 

document.URL //获取当前页面的URL,可读写 

document.anchors[0]或document.anchors["anchName"] //访问页面中所有的锚 

document.forms[0]或document.forms["formName"] //访问页面中所有的表单 

document.images[0]或document.images["imgName"] // 访问页面中所有的图像 

document.links [0]或document.links["linkName"] //访问页面中所有的链接 

document.applets [0]或document.applets["appletName"] //访问页面中所有的Applet 

document.embeds [0]或document.embeds["embedName"] //访问页面中所有的嵌入式对象 

document.write(); 或document.writeln(); //将字符串插入到调用它们的位置

location对象

location对象:表示载入窗口的URL,也可用window.location引用它 

location.href //当前载入页面的完整URL,如http://www.somewhere.com/pictures/index.htm 

location.portocol //URL中使用的协议,即双斜杠之前的部分,如http 

location.host //服务器的名字,如www.wrox.com 

location.hostname //通常等于host,有时会省略前面的www 

location.port //URL声明的请求的端口,默认情况下,大多数URL没有端口信息,如8080 

location.pathname //URL中主机名后的部分,如/pictures/index.htm 

location.search //执行GET请求的URL中的问号后的部分,又称查询字符串,如?param=xxxx 

location.hash //如果URL包含#,返回该符号之后的内容,如#anchor1 

location.assign("http:www.baidu.com"); //同location.href,新地址都会被加到浏览器的历史栈中 

location.replace("http:www.baidu.com"); //同assign(),但新地址不会被加到浏览器的历史栈中,不能通过back和forward访问 

location.reload(true | false); //重新载入当前页面,为false时从浏览器缓存中重载,为true时从服务器端重载,默认为false

navigator对象

 `navigator`对象:包含大量有关Web浏览器的信息,在检测浏览器及操作系统上非常有用,也可用window.navigator引用它 

`navigator.appCodeName` //浏览器代码名的字符串表示 

navigator.appName //官方浏览器名的字符串表示 

navigator.appVersion //浏览器版本信息的字符串表示 

navigator.cookieEnabled //如果启用cookie返回true,否则返回false 

navigator.javaEnabled //如果启用java返回true,否则返回false 

navigator.platform //浏览器所在计算机平台的字符串表示 

navigator.plugins //安装在浏览器中的插件数组 

navigator.taintEnabled //如果启用了数据污点返回true,否则返回false 

navigator.userAgent //用户代理头的字符串表示

screen对象

 screen对象:用于获取某些关于用户屏幕的信息,也可用window.screen引用它 

 screen.width/height //屏幕的宽度与高度,以像素计 

 screen.availWidth/availHeight //窗口可以使用的屏幕的宽度和高度,以像素计 

 screen.colorDepth //用户表示颜色的位数,大多数系统采用32位 

 window.moveTo(0, 0); 

 window.resizeTo(screen.availWidth, screen.availHeight); //填充用户的屏幕

BOM和DOM的结构关系示意图

The above is the detailed content of Detailed explanation of BOM and DOM definitions and usage examples in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn