为什么 CSS 中 #footer > h3 {...} 是低效的

2014-03-11 12:35:35 +08:00
 Part
DOM 定位到 #footer 之后范围应该很小了,而且一般 footer 内容应该很少。


还有这些:
body > * {...}
ul > li > a {...}
#footer > h3 {...}
ul#top_blue_nav {...}
#searbar span.submit a { ... }
.target #target-node { ... }
2385 次点击
所在节点    问与答
6 条回复
nigelvon
2014-03-11 12:39:58 +08:00
因为解释器是从右往左解释的。
zzNucker
2014-03-11 12:40:03 +08:00
这个问题。。。 你搜一下CSS匹配方式就知道了。
slixurd
2014-03-11 12:43:10 +08:00
一拖出去搜 #footer > h3 low performance就搜到google develops的文章了
而且也有解释,实际上就是后代选择器,子元素/兄弟选择器效率低而已

Descendant selectors are inefficient because, for each element that matches the key, the browser must also traverse up the DOM tree, evaluating every ancestor element until it finds a match or reaches the root element. The less specific the key, the greater the number of nodes that need to be evaluated.

Child and adjacent selectors are inefficient because, for each matching element, the browser has to evaluate another node. It becomes doubly expensive for each child selector in the rule. Again, the less specific the key, the greater the number of nodes that need to be evaluated. However, while inefficient, they are still preferable to descendant selectors in terms of performance.
Part
2014-03-11 12:45:53 +08:00
learnshare
2014-03-11 12:52:43 +08:00
要让选择器匹配到的元素最少,或者匹配方式(如从右到左)最直接(就是少用嵌套、* 或者其他关系选择器)。

效率高不高,是要看浏览器的匹配算法的。有兴趣可以去研究浏览器原理/算法相关的东西,挺复杂的。
otakustay
2014-03-11 14:15:56 +08:00
保证最右边那个是tag、#id或.class之一,效率就高了,其它情况([attr]、*之类)效率就低
所以光说#footer > h3,这货效率一点不低,因为>只要往上找一级父元素就行,也没有更多更复杂的selector存在

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/103788

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX