mirror of
https://gitee.com/vant-contrib/vant.git
synced 2025-04-06 03:57:59 +08:00
44 lines
900 B
TypeScript
44 lines
900 B
TypeScript
import { isDef } from '..';
|
|
import { isNumeric } from '../validate/number';
|
|
|
|
export function addUnit(value?: string | number): string | undefined {
|
|
if (!isDef(value)) {
|
|
return undefined;
|
|
}
|
|
|
|
value = String(value);
|
|
return isNumeric(value) ? `${value}px` : value;
|
|
}
|
|
|
|
// cache
|
|
let rootFontSize: number;
|
|
|
|
function getRootFontSize() {
|
|
if (!rootFontSize) {
|
|
const doc = document.documentElement;
|
|
const fontSize =
|
|
doc.style.fontSize || window.getComputedStyle(doc).fontSize;
|
|
|
|
rootFontSize = parseFloat(fontSize);
|
|
}
|
|
|
|
return rootFontSize;
|
|
}
|
|
|
|
function convertRem(value: string) {
|
|
value = value.replace(/rem/g, '');
|
|
return +value * getRootFontSize();
|
|
}
|
|
|
|
export function unitToPx(value: string | number): number {
|
|
if (typeof value === 'number') {
|
|
return value;
|
|
}
|
|
|
|
if (value.indexOf('rem') !== -1) {
|
|
return convertRem(value);
|
|
}
|
|
|
|
return parseFloat(value);
|
|
}
|