这是一个非常学术的问题。我想知道浏览器是如何实现的,以及使用什么数据结构或算法将 CSS 选择器映射到特定的 DOM 元素。是通过哈希表来完成的吗? DOM 子节点如何知道应用于父节点的样式也应用于其自身等等。我一直在 Mozilla 开发人员中心查看,但没有找到任何内容。任何有关该主题的文档或书籍将不胜感激...谢谢!
This is a pretty academic question. I'm wondering how the browser is implemented as in what data structure or algorithm is used to map a CSS selector to a particular DOM element. Is it accomplished through a hash table? How does DOM child node knows that the style applied to parent also applies to itself etc. I've been looking at Mozilla developer center and haven't found anything. Any documentations or books on the subject would be much appreciated... thanks!
发布评论
评论(4)
匹配回答问题“哪些选择器与给定节点匹配”,而不是“哪些节点与选择器匹配”。这使您可以简单地根据当前节点评估选择器的每个部分(比较节点名称/ID/类)。后代组合器和继承是通过扫描父节点来完成的。
如果您对接下来发生的事情感兴趣,WebKit 博客有不错的系列: WebCore渲染基础知识
Matching answers question "which selectors match given node", not "which nodes match a selector". This lets you simply evaluate each part of a selector against current node (compare node name/ID/class). Decendant combinator and inheritance are done through scanning of parent nodes.
If you're interested what happens next, WebKit blog had nice series: WebCore rendering basics
所以这里是稀缺的文档:
从你的问题来看,你似乎应该首先了解更多关于 CSS 应该如何工作的信息(例如什么是规则特异性、计算样式)。
So here are the scarce docs:
From your question it seems that you should first learn more about how CSS is supposed to work (e.g. what is rule specificity, computed style).
你提到了 Mozilla。在特定的具体实现的上下文中回答您的问题当然比在所有可能的实现的抽象概念中更容易。
我想对于 FF2 来说,你的问题的直接答案可能是 风格Firefox 源代码的目录。在该目录中搜索 "hashtable" 在 7 个文件中产生 111 个结果。
我确信哈希表与渲染 CSS 样式所涉及的一些过程广泛相关。
因此,对您的问题的简短回答是:“是的,但它不仅仅是哈希表。”
You mention Mozilla. It is certainly easier answer your question in the context of a particular concrete implementation, rather than the abstract notion of all possible implementations.
I suppose the direct answer to your question, for FF2, is likely to be in the style directory of the firefox source code. A search within that directory for "hashtable" yields 111 results in 7 files.
I feel confident that hashtables are broadly associated with some of the processes involved in rendering CSS styles.
So the short answer to your question is, "Yes, but there's more to it than just hash tables."
W3C 从定义的角度提供了一种通用方法,我认为它提供了丰富的信息:
W3C provides a general approach from a definition standpoint which I find informative: