DOM

来源:互联网 发布:淘宝整机烈士墙2016 编辑:程序博客网 时间:2024/06/01 22:11

DOM 是这样规定的:
整个文档是一个文档节点
每个 XML 标签是一个元素节点
包含在 XML 元素中的文本是文本节点
每一个 XML 属性是一个属性节点
注释属于注释节点
nodeType
元素 1
属性 2
文本 3
注释 8
文档 9

元素节点的 nodeName 与标签名相同
属性节点的 nodeName 是属性的名称
文本节点的 nodeName 永远是 #text
文档节点的 nodeName 永远是 #document

元素节点的 nodeValue 是 undefined
文本节点的 nodeValue 是文本自身
属性节点的 nodeValue 是属性的值

attributes
parentNode
childNodes
firstChild
lastChild
nextSibling
previousSibling

1、节点操作

document.doctypedocument.documentElementdocument.headdocument.titledocument.bodydocument.getElementById('idname')document.querySelector('div')

2、节点列表操作

document.getElementsByClassName('className')document.getElementsByTagName('tagName')document.getElementsByTagNameNS(namespace, name) document.getElementsByName('tagName')document.querySelectorAll('tagName')document.scriptsdocument.embedsdocument.formsdocument.linksdocument.images

3、class操作

el.classList.add(className)el.classList.remove(className)el.classList.contains(className)el.classList.toggle(className)

4、节点操作
创建节点

var el = document.createElement('tagName')

克隆节点

el.cloneNode(true)//要其子节点//默认为false,不要其子节点

添加一个节点

parent.appendChild(el)//在指定节点前添加节点parent.insertBefore(el, parent.childNodes[1])//节点前插入el.insertAdjacentHTML('beforeBegin',htmlString)//节点中,第一个子节点前插入el.insertAdjacentHTML('afterBegin',htmlString)//节点后插入el.insertAdjacentHTML('afterEnd',htmlString)//节点中,最后一个节点后插入el.insertAdjacentHTML('beforeEnd',htmlString)

节点父节点

el.parentNode

子节点

el.firstChild//第一个子节点el.lastChild//最后一个子节点el.children//所有的子节点,返回数组

相邻节点

el.previousSiblingel.previousElementSibling//前一个元素节点el.nextSiblingel.nextElementSibling

删除节点

el.parentNode.removeChild(el); removeAttribute() removeAttributeNode()

5、属性

el.addAttribute('name','value')el.getAttribute('name')getAttributeNode()

6、 内容的设置

el.innerHTMLel.outerHTML//包括括节点自身el.innerTextel.textContent//获得值含有空格

7、样式
获取样式

window.getComputedStyle(el, '')['font-size']window.getComputedStyle(el, ':after')//ie8window.currentStyle(el)

设置样式
el.style.fontSize = ‘16px’
8、位置设置

// getBoundingClientRect返回一个对象,包含top,left,right,bottom,width,height// width、height 元素自身宽高// top 元素上外边界距窗口最上面的距离// right 元素右外边界距窗口最上面的距离// bottom 元素下外边界距窗口最上面的距离// left 元素左外边界距窗口最上面的距离// width 元素自身宽(包含border,padding) // height 元素自身高(包含border,padding) // 元素在页面上的偏移量var rect = el.getBoundingClientRect()return {  top: rect.top + document.body.scrollTop,  left: rect.left + document.body.scrollLeft}// 元素自身宽(包含border,padding) el.offsetWidth// 元素自身高(包含border,padding) el.offsetHeight// 元素的左外边框至包含元素的左内边框之间的像素距离el.offsetLeft// 元素的上外边框至包含元素的上内边框之间的像素距离el.offsetTop //通常认为 <html> 元素是在 Web 浏览器的视口中滚动的元素(IE6 之前版本运行在混杂模式下时是 <body> 元素) //因此,带有垂直滚动条的页面总高度就是 document.documentElement.scrollHeight// 在没有滚动条的情况下,元素内容的总高度scrollHeight// 在没有滚动条的情况下,元素内容的总宽度scrollWidth// 被隐藏在内容区域左侧的像素数。通过设置这个属性可以改变元素的滚动位置scrollLeft// 被隐藏在内容区域上方的像素数。通过设置这个属性可以改变元素的滚动位置scrollTop// 视口大小// ie9+var pageWidth = window.innerWidth,    pageHeight = window.innerHeight;if (typeof pageWidth != "number"){   // ie8  if (document.compatMode == "CSS1Compat"){    pageWidth = document.documentElement.clientWidth;    pageHeight = document.documentElement.clientHeight;  } else {     // ie6混杂模式    pageWidth = document.body.clientWidth;    pageHeight = document.body.clientHeight;  }}

9、事件

// 绑定事件// ie9+el.addEventListener(eventName, handler , Booleans); // Booleans默认false(事件在冒泡阶段执行),true(事件在捕获阶段执行)// ie8el.attachEvent('on' + eventName, function(){  handler.call(el);});// 移除事件// ie9+el.removeEventListener(eventName, handler); // ie8el.detachEvent('on' + eventName, handler);// 事件触发if (document.createEvent) {  // ie9+  var event = document.createEvent('HTMLEvents');  event.initEvent('change', true, false);  el.dispatchEvent(event);} else {  // ie8  el.fireEvent('onchange');}// event对象var event = window.event||event;// 事件的目标节点var target = event.target || event.srcElement;// 事件代理ul.addEventListener('click', function(event) {  if (event.target.tagName.toLowerCase() === 'li') {    console.log(event.target.innerHTML)  }});

10、加载

function ready(fn) {  if (document.readyState != 'loading'){    // ie9+    document.addEventListener('DOMContentLoaded', fn);  } else {    // ie8    document.attachEvent('onreadystatechange', function() {      if (document.readyState != 'loading'){        fn();      }    });  }}

11、去掉空格

// ie8string.replace(/^\s+|\s+$/g, '');// ie9+string.trim();

12、绑定上下文

// ie8fn.apply(context, arguments);// ie9+fn.bind(context);

13、ajax

// GETvar request = new XMLHttpRequest();request.open('GET', 'user.php?fname=Bill&lname=Gates', true); // false(同步)request.send();// ie8request.onreadystatechange = function() {  if (this.readyState === 4) {    if (this.status >= 200 && this.status < 400) {      // Success!      var data = JSON.parse(this.responseText);    } else {      // 错误    }  }};// ie9+request.onload = function() {  if (request.status >= 200 && request.status < 400) {    // Success!    var data = JSON.parse(request.responseText);  } else {    // 服务器返回出错  }};request.onerror = function() {  // 连接错误};// POSTvar request = new XMLHttpRequest(); request.open('POST', 'user.php', true); // false(同步)request.setRequestHeader("Content-type","application/x-www-form-urlencoded");request.send(dataString);

14、json处理

JSON.parse(string);JSON.String(Object)

15、遍历节点

function forEach( nodeList, callback ) {  if(Array.prototype.forEach){    // ie9+    Array.prototype.forEach.call( nodeList, callback );  }else {    // ie8    for (var i = 0; i < nodeList.length; i++){      callback(nodeList[i], i);    }  }}forEach(document.querySelectorAll(selector),function(el, i){})
原创粉丝点击