unit.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { isDef, inBrowser } from '..';
  2. import { isNumeric } from '../validate/number';
  3. export function addUnit(value) {
  4. if (!isDef(value)) {
  5. return undefined;
  6. }
  7. value = String(value);
  8. return isNumeric(value) ? value + "px" : value;
  9. } // cache
  10. var rootFontSize;
  11. function getRootFontSize() {
  12. if (!rootFontSize) {
  13. var doc = document.documentElement;
  14. var fontSize = doc.style.fontSize || window.getComputedStyle(doc).fontSize;
  15. rootFontSize = parseFloat(fontSize);
  16. }
  17. return rootFontSize;
  18. }
  19. function convertRem(value) {
  20. value = value.replace(/rem/g, '');
  21. return +value * getRootFontSize();
  22. }
  23. function convertVw(value) {
  24. value = value.replace(/vw/g, '');
  25. return +value * window.innerWidth / 100;
  26. }
  27. function convertVh(value) {
  28. value = value.replace(/vh/g, '');
  29. return +value * window.innerHeight / 100;
  30. }
  31. export function unitToPx(value) {
  32. if (typeof value === 'number') {
  33. return value;
  34. }
  35. if (inBrowser) {
  36. if (value.indexOf('rem') !== -1) {
  37. return convertRem(value);
  38. }
  39. if (value.indexOf('vw') !== -1) {
  40. return convertVw(value);
  41. }
  42. if (value.indexOf('vh') !== -1) {
  43. return convertVh(value);
  44. }
  45. }
  46. return parseFloat(value);
  47. }