DrillLab
第 45 / 105 道45 / 105 · #288

什么是 DOM,什么是 DOM 事件

What is the DOM and what is DOM event

先自己答,再往下看Answer it yourself first

一句话:DOM 是浏览器把 HTML 解析成的一棵对象树, 每个标签是一个节点; DOM 事件是这棵树上发生的事情 (点击、输入、加载完成), 你可以注册函数去响应。

关键概念要点清:DOM 不是 HTML 本身, 也不属于 JavaScript 语言—— 它是浏览器提供的 API(Web API)。 所以 Node 里没有 document。 这条和 #276 是一组。

为什么「操作 DOM 慢」:不是读写属性本身慢,而是它可能触发重排(reflow)和重绘(repaint)—— 浏览器要重新计算布局、重新画。 在循环里反复读 offsetHeight再改样式,会造成强制同步布局(layout thrashing), 这才是真正的性能杀手。

这直接解释了虚拟 DOM 的价值(见 #330): 它把多次操作合并成一次, 并且尽量只改变化的部分。

会追问:「事件对象上 targetcurrentTarget 什么区别?」——target真正被点的那个元素currentTarget当前监听器挂在哪个元素上事件委托全靠这个区别, 下一题就是。

In one line: the DOM is the tree of objects the browser builds when it parses your HTML — one node per tag. A DOM event is something that happens on that tree (a click, some typing, a load finishing), and you register functions to respond to it.

Be precise about the key point: the DOM is not the HTML itself, and it is not part of the JavaScript language — it is an API the browser hands you (a Web API). That is why Node has no document. This one pairs with #276.

Why “touching the DOM is slow”: reading and writing a property is not the slow part. The cost is that it can trigger reflow and repaint — the browser has to recompute layout and paint again. Reading offsetHeight and then changing a style, over and over inside a loop, causes layout thrashing, and that is the real performance killer.

This is exactly what makes the virtual DOM worth something (see #330): it batches many operations into one and tries to touch only what changed.

Follow-up: “What is the difference between target and currentTarget on the event object?” — target is the element that was actually clicked, currentTarget is the element this listener is attached to. Event delegation rides entirely on that difference, which is the next question.