DOM - msforest/notebook GitHub Wiki

文档对象模型 (DOM)

文档对象模型 (DOM) 将 web 页面与脚本连接起来。用一个逻辑树表示一个文档(document),节点用文档元素表示,每个节点有自己的特性(attribute)、方法和节点之间的关系。

节点之间的关系 dom relation

insertAdjacentHTML

element.insertAdjacentHTML(position, text)

  • 'beforebegin': Before the element itself.
  • 'afterbegin': Just inside the element, before its first child.
  • 'beforeend': Just inside the element, after its last child.
  • 'afterend': After the element itself.
<!-- beforebegin -->
<element>
  <!-- afterbegin -->
  foo
  <!-- beforeend -->
</element>
<!-- afterend -->

Note: The beforebegin and afterend positions work only if the node is in the DOM tree and has a parent element.

classList

class 操作方法有:

  • add(value)
  • contains(value)
  • remove(value)
  • toggle(value)

css 样式定义分三种:

  • 内联样式(inline style)
  • 行内样式(internal style sheet)
  • 外部样式(external style sheet)

获取这些样式的有:style / currentStyle / getComputedStyle

  • style
    • 只能获取内联样式所定义的属性
    • 可读可写可删(getPropertyValue/setProperty/removeProperty)
    • 可通过 cssText 一次性修改元素样式属性值,避免多次 reflow 和 repaint
  • currentStyle
    • 用在兼容 IE 的黑魔法
    • 可以获取上述三种定义的属性及动态改变的属性值
    • 使用 getAttribute 方法取值
    • 只读
  • getComputedStyle
    • 获取计算后的 style, 可获取伪类元素的样式,currentStyle 做不到
    • 同 currentStyle, 获取当前元素所有最终的 css 属性值
    • 使用 getPropertyValue 方法取值
    • 只读

用法:

<style>
  a {
    width: 100px;
  }
</style>
<a style="float:left">text</a>
<script>
  document.querySelector("a").style.float; // left
  document.querySelector("a").style.width; // ''
  document.querySelector("a").style.setProperty("width", "10px", "important");
  document.querySelector("a").style.removeProperty("width");

  document.querySelector("a").currentStyle.getAttribute("cssFloat"); // left
  document.querySelector("a").currentStyle.getAttribute("width"); // 100px

  document.defaultView
    .getComputedStyle(document.querySelector("a"), ":after")
    .getPropertyValue("float"); // left
  document.defaultView
    .getComputedStyle(document.querySelector("a"), null)
    .getPropertyValue("width"); // 100px
</script>

document vs document.documentElement vs node.ownerDocument vs node.ownerDocument.defaultView vs window vs document.defaultView

  • document 是提供给脚本操作 DOM 元素的接口,指向的是整个文档(#document)
  • document.documentElement 指向的是文档的根元素(html),只读属性
  • node.ownerDocument === document 可以快速获取 document,实现其他功能
  • document.defaultView 指向的是提供给脚本的一个全局访问变量,在 js 脚本里就是等于 window
  • node.ownerDocument.defaultView === document.defaultView === window

这也是为什么很多地方都用 document.defaultView.getComputedStyle,而不是直接用 window.getComputedStyle。

⚠️ **GitHub.com Fallback** ⚠️