CSS 数字工厂函数

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2015.

CSS 数字工厂函数(例如 CSS.em()CSS.turn())是返回 CSSUnitValue 的方法,其中值为实际参数,单位是所使用的方法名称。这些函数创建新的数值比使用 CSSUnitValue() 构造函数更加简洁。

语法

js
CSS.number(number)
CSS.percent(number)

// <length>
CSS.em(number)
CSS.ex(number)
CSS.ch(number)
CSS.ic(number)
CSS.rem(number)
CSS.lh(number)
CSS.rlh(number)
CSS.vw(number)
CSS.vh(number)
CSS.vi(number)
CSS.vb(number)
CSS.vmin(number)
CSS.vmax(number)
CSS.cm(number)
CSS.mm(number)
CSS.Q(number)
CSS.in(number)
CSS.pt(number)
CSS.pc(number)
CSS.px(number)

// <angle>
CSS.deg(number)
CSS.grad(number)
CSS.rad(number)
CSS.turn(number)

// <time>
CSS.s(number)
CSS.ms(number)

// <frequency>
CSS.Hz(number)
CSS.kHz(number)

// <resolution>
CSS.dpi(number)
CSS.dpcm(number)
CSS.dppx(number)

// <flex>
CSS.fr(number)

示例

我们使用 CSS.vmax() 数字工厂函数来创建 CSSUnitValue

js
const height = CSS.vmax(50);

console.log(height); // CSSUnitValue {value: 50, unit: "vmax"}
console.log(height.value); // 50
console.log(height.unit); // vmax

在此示例中,我们使用 CSS.px() 工厂函数给元素设置外边距:

js
myElement.attributeStyleMap.set("margin", CSS.px(40));
const currentMargin = myElement.attributeStyleMap.get("margin");
console.log(currentMargin.value, currentMargin.unit); // 40, 'px'

规范

Specification
CSS Object Model (CSSOM)
# namespacedef-css

浏览器兼容性

BCD tables only load in the browser

参见