JavaScript——DOM

通过DOM控制节点的布局、样式、属性、事件进行交互开发

Posted by page on July 7, 2020

DOM

获取元素

  • document.documentElement

  • doucment.body

  • document.getElementById()

  • context.getElementsByTagName()

  • context.getElementByName()

拓展

  • ele.getElemnentsByClassName()

  • ele.querySelector()/querySelectorAll()

  • ele.closest()

节点关系

  • node.parentNode

  • node.childNodes/扩展ele.children

  • node.firstChild/扩展ele.firstElementChild

  • node.lastChild/扩展ele.lastElementChild

  • node.nextSibling/扩展ele.nextElementSibling

  • node.previousSibling/扩展ele.previousElementSibling

节点操作

  • document.createElement(“img”)

  • document.createDocumentFragment()

  • node.cloneNode(true)

  • node.appendChild()

  • node.insertBefore()

  • node.removeChild(this.lastChild)

  • node.replaceChild(newNode,this.firstChild)

另有Text节点操作、table节点操作

节点属性

  • ele.get/set/removeAttribute() 标签属性

  • ele.id/title/className 标签Id与Class

  • ele.innerHTML/outerHTML/insertAdjacentHTML(“after/before&begin/end”,”html字符串”)

  • ele.innerText/textContent

  • ele.tagName.toLowerCase 标签名

DOM盒模型

client客户区(不含边框与滚动条)

  • ele.clientHeight/clientWidth 元素客户区大小

  • ele.clientTop/clientLeft 元素边框大小

offset偏移

  • ele.offsetHeight/offsetWidth 布局大小

  • ele.offsetTop/offsetLeft 相对位置偏移量

scroll滚动

  • ele.scrollHeight/scrollWidth 内部内容大小

  • ele.scrollTop/scrollLeft 内部滚动条位置

DOM事件

事件流

  • 事件冒泡:默认事件流

  • 事件捕获:利用捕获原理进行事件代理,配合事件对象target属性事件处理

事件处理程序

ele.onclick = func
ele.addEventListener/removeEventListener(func)
ele.attach/detach("onclick",func) IE8-

事件对象

  • e.type

  • e.target

  • e.currentTarget

  • e.preventDefault() 取消默认行为

  • e.stopPropagration() 停止事件流

  • 另有IE8-事件对象属性方法

事件类型

UI事件

  • load 元素加载完成触发

  • scroll 仅支持window,监测页面滚动

焦点事件

  • focus

  • focusin

  • focusout

鼠标事件

  • click/dbclick 点击

  • mousedown/mouseup 任意键按下/弹起

  • mouseover/mouseuot 移出移入/移出

  • mousemove 移动

  • mouseenter/mouseleave 首次移出/移动

  • mousewhell 滚轮事件

鼠标事件执行顺序:mousedown => mouseup => click(左键时)

手指事件

  • touchstart

  • touchmove

  • touchend

  • touchcancel

注:默认存在穿透问题,需 event.preventDefault()

事件属性

  • e.clientX/Y 相对客户区位置

  • e.offsetX/Y 相对内容区位置

  • e.pageX/Y 相对页面位置

  • e.screenX/Y 相对屏幕位置

  • e.shiftKey/ctrlKey/altKey/metaKey 是否使用各种辅助键

  • e.button 返回0,1,2对应mousedown/up的主键,滚轮键,右键

  • e.wheelDelta 返回滚动值(正负120倍数)

键盘事件

  • keydown/up 键盘键按下/弹出

  • keypress 键盘按下状态

判断 event.target 为document.body过滤掉表单输入按键操作

键盘事件属性

e.key 键的标准标识值

e.code 键的物理按键标识

HTML5事件

  • window.beforeunload 刷新/关闭网页

  • window.hashchange 哈希值改变触发(location.hash)

API

  • ele.getBoundingClientRect()

    返回一个对象,其top,left…属性为DOM元素相对视口(client)位置值

    常用于计算鼠标cleintX/Y相对于元素位置

DOM对象

window

文档窗口对象(innerWidth/innerHeight)

Document

文档对象

Element

节点类型为Element的对象:元素;

Node

DOM的基本对象:节点;所有DOM API相关对象都会基础node的属性/方法

  • node.contains(childNode):判断是否节点的后代节点;

DOMTokenList

通过element.classList返回的dom标记组成的类数组

  • DOMTokenList.contains(‘className’):判断类名是否包含于class标记列表

MutationObserver

监听DOM树更改

  1. 创建监听器处理

    const observer = new MutationObserver((mutationList) => {
    mutationList.forEach((mutation) => {
        switch(mutation.type) {
          case 'childList':
            ...
            break;
          case 'attributes':
            /* mutation.target 中某节点的一个属性值被更改;
               该属性名称在 mutation.attributeName 中,
               该属性之前的值为 mutation.oldValue */
            break;
        }
      });
    });
    
  2. 为DOM元素绑定监听

    // 监听更改类型 childList: 子节点增删 subtree: 后代节点增删 attributes: 当前DOM属性变动
    const observeTypes = { childList: true, subtree: true, attributes: true };
    observer.observe($element, observeTypes);
    
  3. 断开监听器

    observer.disconnect();
    

常见场景

在父元素下监听将来img元素的onload事件

  • 实现:事件代理+事件捕获
$parent.addEventListener('load', e => {
  // 注意判断img源,否则多个img下会触发多次事件
  if(e.target.tagName.toLowerCase() === 'img')
  // 事件处理
}, true);