mirror of
https://github.com/youzan/vant.git
synced 2025-10-22 11:54:02 +00:00
chore: move utils
This commit is contained in:
43
src-next/utils/format/unit.ts
Normal file
43
src-next/utils/format/unit.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
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);
|
||||
}
|
Reference in New Issue
Block a user