Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Web API - CSS Typed Object Model #69

Open
taoliujun opened this issue Mar 6, 2024 · 1 comment
Open

Web API - CSS Typed Object Model #69

taoliujun opened this issue Mar 6, 2024 · 1 comment
Labels

Comments

@taoliujun
Copy link
Owner

CSS Typed OM

MDN: https://developer.mozilla.org/en-US/docs/Web/API/CSS_Typed_OM_API

CSS Typed OM全称CSS Typed Object Model,提供了一系列访问和操作CSS值的方法。

在以往,使用HTMLElement.style管理元素的样式,它只是一个string类型,管理很笨拙,可读性也差。而本API将CSS值解析为可读性很高的对象,据此可以科学的管理它。

HTMLElement.style相比,本API更有可读性,性能更高。

接口

有公用类型CSSStyleValue和若干特殊类型如CSSImageValueCSSKeywordValue等组成。

CSSStyleValue

它是所有CSS值类型的公用类型,提供了parse方法将一个字符串解析成样式对象,例:

// 返回 CSSStyleValue 类型
CSSStyleValue.parse('color', '#f00');
// 返回 CSSTransformValue 类型
CSSStyleValue.parse('transform', 'translate(30px, 20px) rotate(45deg)');

CSSKeywordValue

CSS保留关键字类型如initial,例:

// 返回 CSSKeywordValue {value: 'normal'} 类型,因为normal是保留关键字。
$0.computedStyleMap().get('font-style');

其他类型见MDN

StylePropertyMapReadOnly

提供getgetAll等方法读取样式。

StylePropertyMap

继承于StylePropertyMapReadOnly,提供appendset等方法操作样式,如:

// 将元素的文本颜色设置为红色
$0.attributeStyleMap.set('color', 'red');

方法和属性

computedStyleMap

HTMLelement.computedStyleMap()返回StylePropertyMapReadOnly类型。

attributeStyleMap

HTMLElement.attributeStyleMap返回StylePropertyMap类型。

示例

示例:https://taoliujun.github.io/example/web-api/CSS_Typed_OM_API/index.html

  1. 在例子中,打印出元素所有的样式,或打印出指定的样式:

image

  1. 改变元素的颜色样式:

image

@taoliujun
Copy link
Owner Author

开发富文本编辑器、代码可视化的场景中,可以使用此API改变元素样式,并在提交时收集样式。在渲染的地方解析这些值并渲染。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant