Document 对象
1. 概述
每个载入浏览器的 HTML 文档都会成为 Document 对象。
即, Document对象 代表 整个HTML文档.
Document 对象使我们可以从脚本中对HTML页面中的所有元素进行访问。
提示:
Document 对象是 Window 对象的一部分,
可通过 window.document 属性对其进行访问。
参考: http://www.w3school.com.cn/htmldom/dom_obj_document.asp
2. 集合
3. 属性
body 属性和方法
- appendChild()
- removeChild()
- getElementByTagName()
- bgColor 文档背景色
- background 文档背景图
- innerText
- innerHTML
- onload事件
- onunload事件 (用于关闭页面后, 向服务器发请求消除session)
- onbeforeunload事件
- onselectstart 事件 , 选择body内的内容时
- onscroll事件, 拉动滚动条时, (浮动广告跟着滚动条走)
① 说明
提供对 <body> 元素的直接访问。
对于定义了框架集的文档,该属性引用最外层的 <frameset>。
② 参考
http://www.w3school.com.cn/htmldom/htmldom_reference.asp
http://www.w3school.com.cn/htmldom/dom_obj_body.asp
③ innerText 与 innerHTML的区别
innerText 把字符串原样显示
innerHTML 字符串会被JavaScript引擎解析
④ 跟着滚动条跑的浮动广告 - onscroll事件
<html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <script type="text/javascript"> var ad; window.onload = function() { ad = document.getElementById("ad"); } window.onscroll = function() { ad.style.top = document.body.scrollTop + 50; } </script> <style type="text/css"> div { width: 200px; height: 200px; background-color: green; position: absolute; } </style> </head> <body> <div id="ad">我是讨厌的广告</div> <textarea rows="1000"> ....... </textarea> </body> </html>
4. 方法
1) write() / writeln()
向文档写 HTML 表达式 或 JavaScript 代码。
writeln()等同于 write() 方法,
不同的是在每个表达式之后写一个换行符("\n\r")。
2) open(mimetype,replace)
该方法将擦除当前 HTML 文档的内容,开始一个新的文档,
新文档用 write() 方法或 writeln() 方法编写。
3) close()
可关闭一个由 document.open 方法打开的输出流,
并显示选定的数据。
4) 获取文档中元素
① document.getElementById(id)
返回对拥有指定 id 的 第一个对象的引用。
② document.getElementsByName(name)
返回带有指定名称的 对象集合。
③ element.getElementsByTagName(tagname)
返回带有指定标签名的 对象集合。
<div id="links"> <a href="#">1</a> <a href="#">1</a> </div> <script type="text/javascript"> var links = document.getElementById("links"); console.info( links.getElementsByTagName("a") ); </script>
5. 节点操作
元素(节点)的 创建/添加/删除.
注:
HTML DOM 和 XML DOM 都遵循相同的DOM规范
因此, 可参看 XML DOM
1) 动态创建 HTML元素
① document.createElement(tagName)
② parentElement.appendChild(newChild)
③ parentElement.removeChild(oldChild)
<body> <input type="button" value="动态创建超链接" onclick="createLink()"/> <input type="button" value="删除超链接" onclick="removeLink()"/> <div id="showArea" style="background-color: gray; height: 200px; width: 200px;" > 1 </div> </body>
<script type="text/javascript"> var showArea; window.onload = function() { showArea = document.getElementById("showArea"); } function createLink() { // 创建 超链接元素 var linkElement = document.createElement("a"); // 给 超链接元素 添加属性 linkElement.href = "http://www.baidu.com"; linkElement.innerHTML = "baidu"; // 指定位置 // 将超链接 挂载到div上 -- 添加节点 showArea.appendChild(linkElement); } function removeLink() { var bodyElement = document.getElementsByTagName("body")[0]; bodyElement.removeChild(showArea); } </script>