V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
Part
V2EX  ›  问与答

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

  •  
  •   Part · 2014-03-11 12:35:35 +08:00 · 2379 次点击
    这是一个创建于 3714 天前的主题,其中的信息可能已经有所发展或是发生改变。
    DOM 定位到 #footer 之后范围应该很小了,而且一般 footer 内容应该很少。


    还有这些:
    body > * {...}
    ul > li > a {...}
    #footer > h3 {...}
    ul#top_blue_nav {...}
    #searbar span.submit a { ... }
    .target #target-node { ... }
    6 条回复    1970-01-01 08:00:00 +08:00
    nigelvon
        1
    nigelvon  
       2014-03-11 12:39:58 +08:00   ❤️ 1
    因为解释器是从右往左解释的。
    zzNucker
        2
    zzNucker  
       2014-03-11 12:40:03 +08:00   ❤️ 1
    这个问题。。。 你搜一下CSS匹配方式就知道了。
    slixurd
        3
    slixurd  
       2014-03-11 12:43:10 +08:00   ❤️ 1
    一拖出去搜 #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
        4
    Part  
    OP
       2014-03-11 12:45:53 +08:00   ❤️ 1
    learnshare
        5
    learnshare  
       2014-03-11 12:52:43 +08:00   ❤️ 1
    要让选择器匹配到的元素最少,或者匹配方式(如从右到左)最直接(就是少用嵌套、* 或者其他关系选择器)。

    效率高不高,是要看浏览器的匹配算法的。有兴趣可以去研究浏览器原理/算法相关的东西,挺复杂的。
    otakustay
        6
    otakustay  
       2014-03-11 14:15:56 +08:00   ❤️ 1
    保证最右边那个是tag、#id或.class之一,效率就高了,其它情况([attr]、*之类)效率就低
    所以光说#footer > h3,这货效率一点不低,因为>只要往上找一级父元素就行,也没有更多更复杂的selector存在
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   960 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 21:12 · PVG 05:12 · LAX 14:12 · JFK 17:12
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.