CSS 卡尔克 
已执行: https://drafts.csswg.org/cs-values-4/ (中文(简体) ) 于2023-02-17查阅
使用量
添加 CSS 计算 对您的项目:
npm install @csstools/css-calc @csstools/css-parser-algorithms @csstools/css-tokenizer --save-dev
有字符串值 :
import { calc } from '@csstools/css-calc';
// '20'
console.log(calc('calc(10 * 2)'));
有组件值 :
import { stringify, tokenizer } from '@csstools/css-tokenizer';
import { parseCommaSeparatedListOfComponentValues } from '@csstools/css-parser-algorithms';
import { calcFromComponentValues } from '@csstools/css-calc';
const t = tokenizer({
css: 'calc(10 * 2)',
});
const tokens = [];
{
while (!t.endOfFile()) {
tokens.push(t.nextToken());
}
tokens.push(t.nextToken()); // EOF-token
}
const result = parseCommaSeparatedListOfComponentValues(tokens, {});
// filter or mutate the component values
const calcResult = calcFromComponentValues(result, { precision: 5, toCanonicalUnits: true });
// filter or mutate the component values even further
const calcResultStr = calcResult.map((componentValues) => {
return componentValues.map((x) => stringify(...x.tokens())).join('');
}).join(',');
// '20'
console.log(calcResultStr);
选项
precision 数字 :
这个 precision 选项是若干小数.
默认精度相当高.
它旨在高到足以使取舍在浏览器中无法被注意.
在科学标记中序列化的数值没有变化.
可以设置为更低的号码以适应您的需要.
import { calc } from '@csstools/css-calc';
// '0.3'
console.log(calc('calc(1 / 3)', { precision: 1 }));
// '0.33'
console.log(calc('calc(1 / 3)', { precision: 2 }));
// '1.0000000000000001e-20'
console.log(calc('calc(1e-10 * 1e-10)'));
globals 数字 :
传递全局值为密钥值对的映射.
示例:相对颜色语法(
lch(from pink calc(l / 2) c h))将彩色通道信息曝光为标识符. 通过环球l, (中文(简体) ),c财务报告和审定财务报表h可以解决巢穴问题calc()对.
import { calc } from '@csstools/css-calc';
const globals = new Map([
['a', '10px'],
['b', '2rem'],
]);
// '20px'
console.log(calc('calc(a * 2)', { globals: globals }));
// '6rem'
console.log(calc('calc(b * 3)', { globals: globals }));
toCanonicalUnits 数字 :
默认情况下, 此软件包将尝试保存单位 . 这样做的修炼非常简单. 我们用我们遇到的第一个单位 尝试把其他维度转换成那个单位.
这更符合用户对 CSS dev 工具的期望.
如果您想要将输出关闭于 CSS 序列化值, 您可以通过 toCanonicalUnits: true。 。 。 .
import { calc } from '@csstools/css-calc';
// '20hz'
console.log(calc('calc(0.01khz + 10hz)', { toCanonicalUnits: true }));
// '20hz'
console.log(calc('calc(10hz + 0.01khz)', { toCanonicalUnits: true }));
// '0.02khz' !!!
console.log(calc('calc(0.01khz + 10hz)', { toCanonicalUnits: false }));
// '20hz'
console.log(calc('calc(10hz + 0.01khz)', { toCanonicalUnits: false }));