CSS Typed Object Model API
The parse() static method of the CSSNumericValue interface creates a CSSNumericValue from a string of CSS, such as "42px" or "calc(50% + 10px)".
[!NOTE] This method is only available in Window contexts, not in Worker or Worklet contexts. All other methods of the
CSSNumericValueinterface are available in workers and worklets.
Syntax
CSSNumericValue.parse(cssText)
Parameters
cssText- : A string containing a single CSS number, percentage, dimension (a number with a unit, such as
42px), or math function, such ascalc(),min(),max(), orclamp().
- : A string containing a single CSS number, percentage, dimension (a number with a unit, such as
Return value
A CSSNumericValue. This is a CSSUnitValue for a number, percentage, or dimension, or one of the CSSMathValue subtypes for a math function.
Exceptions
SyntaxErrorDOMException- : Thrown if
cssTextisn't a single number, percentage, dimension, or math function (for example,"auto","10px 20px", or"var(--size)"), if it uses an unknown unit (such as"10foo"), or if it contains an invalid calculation (such as"calc(1px + 1s)").
- : Thrown if
Description
The string is parsed in the same way as a value in a stylesheet.
Spaces and comments around the value are ignored, and unit names aren't case-sensitive, so " 10PX " gives the same result as "10px".
A number without a unit, such as "7", gives a CSSUnitValue whose unit is "number".
Math functions are also simplified in the same way as in a stylesheet, so terms that can be combined are combined.
For example, "calc(1px + 2px)" gives a CSSMathSum with a single term, 3px.
Terms that can't be combined until the page is laid out, such as 50% and 10px, are kept separate.
Examples
Parsing single values
Numbers, percentages, and dimensions are parsed into a CSSUnitValue:
const length = CSSNumericValue.parse("42.0px");
console.log(length.constructor.name); // "CSSUnitValue"
console.log(length.value); // 42
console.log(length.unit); // "px"
const percentage = CSSNumericValue.parse("50%");
console.log(percentage.unit); // "percent"
Parsing a calculation
A math function is parsed into one of the CSSMathValue subtypes.
Terms that can be combined are combined, so calc(1px + 2px) is simplified to a sum with a single term:
const sum = CSSNumericValue.parse("calc(50% + 10px)");
console.log(sum.constructor.name); // "CSSMathSum"
console.log(sum.toString()); // "calc(50% + 10px)"
const simplified = CSSNumericValue.parse("calc(1px + 2px)");
console.log(simplified.toString()); // "calc(3px)"
Handling a string that isn't a numeric value
try {
CSSNumericValue.parse("auto");
} catch (e) {
console.log(e.name); // "SyntaxError"
}
Specifications
Browser compatibility
See also
- CSSStyleValue.parse_static
- Numeric factory functions
- Using the CSS Typed OM
来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。
