DOM操作

2019-04-17  本文已影响0人  一米阳光kk

什么是DOM( Document Object Model)
DOM定义了表示和修改文档所需的方法。DOM对象即为宿主对象,由浏览器厂商定义,用来操作html和xml功能的一类对象的集合。也有人称DOM是对HTML以及XML的标准编程接口。

DOM基本操作

1. 对节点的增删查改

例:点击不同按钮切换展示不同div

<script type="text/javascript">
var btn = document.getElementsByTagName('button');
var div = document.getElementsByClassName('content');
for(var i = 0; i< btn.length; i++) {
  (function(n){
    btn[n].onclick = function(){
      for(var j = 0; j< btn.length; j++) {
        btn[j].className = '';
        btn[j].style.display= 'none';
      }
      this.className = "active";
      div[n].style.display = "block";
    }
  })(i)
}
</script>
2. 遍历节点树

上面的方法不区分节点类型:包含 文本节点、注释节点、元素节点等各种类型的节点(兼容所有浏览器)

3. 基于 元素节点 树遍历

部分方法IE9以下不兼容

4. 节点类型

数字对应nodeType 返回值

例如:返回一个节点所有的元素节点

function returnElementChild(node) {
  var temp  = { // 定义一个类数组
    length: 0,
    push: Array.prototype.push, // 拥有数组的方法
    splice: Array.prototype.splice // 拥有数组的形式
  }
  var child = node.childNodes, len = child.length
  for(var i = 0; i< len; i++) {
    if(child[i].nodeType === 1) {
      temp.push(child[i])
    }
  }
  return temp;
}
5. 节点的四个属性

节点的一个方法 Node.hasChildNodes();// true or false

DOM 结构树

DOM结构树.png

// document -->HTMLDocument.prototype -->Document.prototype

DOM基本操作

例:封装函数,返回元素e的第n个兄弟节点,n为正,返回后面的兄弟元素节点,n为负,返回前面的,n为0,返回自己

function returnSiblings(e, n) {
  while(e && n) {
    if (n>0) {
      e = e.nextElementSibling;
      n--;
    } else 
    {
      e = e.previousElementSibling;
      n++;
    }
  }
  return e;
}

上面的nextElementSibling/ previousElementSibling有兼容性问题(IE9以下不兼容),考虑用nextSibling可以兼容ie,但是nextsibling返回的不仅仅是元素节点,可能是文本节点,注释节点...

下面兼任处理:

function returnSiblings(e, n) {
  while(e && n) {
    if (n>0) {
      if(e.nextElementSibling) {
        e = e.nextElementSibling;
      } else {
        for(e = e.nextSibling; e && e.nodeType !== 1; e = e.nextSibling);
      }
      n--;
    } else 
    {
      if(e.previousElementSibling) {
         e = e.previousElementSibling;
      } else {
        for(e = e.previousSibling; e && e.nodeType !== 1; e = e.previousSibling);
      }
      n++;
    }
  }
  return e;
}

DOM基本操作--->增 删 改

如:封装函数insertAfter(); 功能类似insertBefore();(可忽略老版本浏览器)

Element.prototype.insertAfter = function(targetNode, afterNode) {
  var beforeNode = afterNode.nextElementSibling;
  if (beforeNode == null) {
    this.appendChild(targetNode);
  }else{
    this.insertBefore(targetNode, beforeNode);
  }
}
function getScrollOffset() {
  if(window.pageXOffset) {
    return {
      x: window.pageXOffset,
      y: window.pageYOffset
    }
  } else {
    retutn {
      x: document.body.scrollLeft + documnet.documentElement.scrollLeft,
      y: document.body.scrollTop + document.documentElement.scrollTop
    }
  }
}
function getViewportOffset() {
  if(window.innerWidth) {
    return {
      w: window.innerWidth,
      h: window.innerHeight
    }
  } else {
    if(document.compatMode === 'BackCompat') { // 怪异模式
      return {
        w: document.body.clientWidth,
        h: document.body.clientHeight
      }
    } else {
      return {
        w: document.documentElement.clientWidth,
        h: document.documentElement.clientHeight
      }
    }
  }
}
<!doctype html>
<html>
    <head></head>
    <body>
        <div style="background: red; width: 100px; height: 100px; left: 100px; top: 100px;position: absolute;"></div>
        <script>
            var div = document.getElementsByTagName('div')[0];
            let box = div.getBoundingClientRect();
            console.log(box);
            div.style.width = "200px";
            console.log(box);
        </script>
    </body>
</html>
image.png

例: 求任意元素相对于文档的坐标getElementPosition

function getElementPosition() {
  
}
var start = document.getElementById('start'); // 开始按钮
var stop = document.getElementById('stop'); // 结束按钮
var timer = 0, key = true;
start.onclick = function() {
   if(key) {
      timer  = setInterval(function(){
       window.scrollBy(0, 10);
      }, 100);
      key = false;
    }
}
stop.onclick = function() {
  clearInterval(timer );
  key = true;
}
脚本化CSS
// div.style 获取的是行间样式,即style="width: 100px;height:200px"上的样式, 没写就没有
var div = document.getElementsByTagName('div')[0];
div.style.width = "200px";
div.style.height = "200px";
div.style.backgroundColor = "red"; // 组合单词background-color变成小驼峰式
div.style.borderWidth = "5px" // 符合属性必须拆解(border-width 是border中的一个属性)
// div.style.border = "5px solid black" 现在浏览器也支持这种写法
var div = document.getElementsByTagName('div')[0];
var computedStyle = window.getComputedStyle(div, null);
console.log(computedStyle.width);

例:封装兼容性方法getStyle(elem, prop)

function getStyle(elem, prop) {
  if(window.getComputedStyle) {
    return window.getComputedStyle(elem, null)[prop];
  } else {
    return elem.currentStyle[prop];
  }
}

getComputedStyle的第二个参数,用来获取伪元素的样式表
如获取div伪元素的宽度:

// div::after{content:""; width: 50px;height:50px; display:inline-block;}
var div = document.getElementsByTagName('div')[0];
window.getComputedStyle(div, "after").width;
上一篇 下一篇

猜你喜欢

热点阅读