CSSOM 与已计算样式

CSSOM 与 计算样式

CSS 对象模型将样式表文本转换为参与真实层叠的实时对象。CSSStyleSheet 保存规则,CSSStyleDeclaration 保存属性声明,Element.get_computed_style() 报告解析后的结果。


解析与附加样式表

CSSStyleSheet.replace_sync() 解析样式表文本;Document.attach_style_sheet() 注册该表以使其规则生效。规则也可以通过 insert_rule()、add_rule() 和 remove_rule() 单独管理:

from aspose_html.dom import Document
from aspose_html.cssom import CSSStyleSheet
doc = Document()
sheet = CSSStyleSheet()
sheet.replace_sync("div { color: red }")
doc.attach_style_sheet(sheet)

规则族

已解析的表格包含类型化规则:CSSStyleRule 用于普通选择器,另外还有 CSSMediaRule、CSSKeyframesRule、CSSFontFaceRule、CSSSupportsRule、CSSImportRule,以及页面/层/命名空间变体,这些规则收集在一个 CSSRuleList 中。parse_stylesheet() 和 parse_rule_text() 直接暴露解析层。

声明与内联样式

每个元素的 style 属性是一个实时的 CSSStyleDeclaration:set_property()、get_property_value()、get_property_priority() 和 item() 读取和写入声明。内联声明优先于任何选择器特异性的作者规则:

from aspose_html.dom import Document
from aspose_html.cssom import CSSStyleSheet
doc = Document()
el = doc.create_element("div")
doc.append_child(el)
sheet = CSSStyleSheet()
sheet.replace_sync("div { color: red }")
doc.attach_style_sheet(sheet)
inline = el.style
inline.set_property("color", "blue")
print(el.get_computed_style().get_property_value("color"))

解析层叠

Element.get_computed_style() 返回一个反映特异性、重要性和继承性的 ComputedStyleDeclaration。标记为 !important 的作者规则胜过非重要的内联声明:

from aspose_html.dom import Document
from aspose_html.cssom import CSSStyleSheet
doc = Document()
el = doc.create_element("div")
doc.append_child(el)
sheet = CSSStyleSheet()
sheet.replace_sync("div { color: red !important }")
doc.attach_style_sheet(sheet)
inline = el.style
inline.set_property("color", "blue")
print(el.get_computed_style().get_property_value("color"))

技巧与最佳实践

  • 在读取计算样式之前附加样式表 — 解析反映当前已附加的样式表
  • 在调试意外获胜者时,使用 get_property_priority() 检查是否存在 !important
  • 每个逻辑样式表保持一个 CSSStyleSheet;CSSRuleList 保持规则顺序,这在特异性相等的平局中很重要
  • 进行继承检查时,先读取父元素的计算值,然后再读取子元素的

常见问题

问题原因修复
计算值忽略了规则工作表从未附加调用 Document.attach_style_sheet()
内联样式意外丢失作者规则包含 !important使用 get_property_priority() 检查
缺少继承值属性不可继承或子项具有本地值本地值始终优先于继承值

FAQ

如何将 CSS 文本解析为对象?

CSSStyleSheet.replace_sync() 用于整张表,或 parse_rule_text() 用于单个规则。

get_computed_style 返回什么?

一个 ComputedStyleDeclaration — 使用 get_property_value() 读取值。

行内样式总是优先吗?

它们会击败任何特异性的作者规则,但会输给标记为 !important 的作者规则。


API Reference 摘要

类/方法描述
CSSStyleSheet.replace_sync就地解析样式表文本
Document.attach_style_sheet在文档中注册工作表
CSSStyleDeclaration.set_property编写声明
CSSStyleDeclaration.get_property_priority检查 !important
Element.get_computed_style解析元素的层叠
parse_stylesheet低级样式表解析

另请参阅

 中文