front-end-interview-handbook/packages/quiz/questions/explain-how-a-browser-deter.../zh-CN.mdx

8 lines
765 B
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: 解释浏览器如何决定什么元素与 CSS 选择器匹配。
---
这个问题与[编写高效的 CSS](/questions/quiz/what-are-some-of-the-gotchas-for-writing-efficient-css) 的问题有关。 浏览器从最右边(关键选择器)到左边匹配选择器。 浏览器根据关键选择器过滤出 DOM 中的元素,并向上遍历其父元素以确定匹配。 选择器链长度越短,浏览器就能越快确定该元素是否与选择器匹配。
例如,使用选择器`p span` 浏览器先找到所有 `<span>` 元素,然后沿其父元素遍历到根节点以找到`<p>` 元素。 对于一个特定的`<span>`,只要它找到一个`<p>`,它就知道这个`<span>`符合选择器,并可以停止遍历它的父元素。