CSS 属性和值 API
Baseline 2024
Newly available
Since July 2024, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.
CSS 属性和值 API(CSS Properties and Values API)——CSS Houdini API 的一部分——允许开发者显式地定义它们的 CSS 自定义属性
,允许设置属性类型检查、默认值以及是否可继承其值。
接口
CSS.registerProperty
-
定义了浏览器应该如何解析
CSS custom properties
。通过 JavaScript 中的CSS.registerProperty
访问该接口。 @property
-
定义了浏览器应该如何解析
CSS custom properties
。通过 CSS 中的@property
at 规则访问该接口。
示例
以下代码在 JavaScript 中使用 CSS.registerProperty
输入一个 CSS 自定义属性
,--my-color
,将其作为一个颜色,然后为其设置一个默认值,并且不允许继承它的值。
js
window.CSS.registerProperty({
name: "--my-color",
syntax: "<color>",
inherits: false,
initialValue: "#c0ffee",
});
可以在 CSS 中使用 @property
at-rule 进行相同的注册:
css
@property --my-color {
syntax: "<color>";
inherits: false;
initial-value: #c0ffee;
}
规范
Specification |
---|
CSS Properties and Values API Level 1 # the-css-property-rule-interface |
CSS Properties and Values API Level 1 # the-registerproperty-function |
浏览器兼容性
api.CSSPropertyRule
BCD tables only load in the browser
api.CSS.registerProperty_static
BCD tables only load in the browser