1
0

index.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // @ts-nocheck
  2. import { isString } from '../isString'
  3. import { isNumeric } from '../isNumeric'
  4. /**
  5. * 单位转换函数,将字符串数字或带有单位的字符串转换为数字
  6. * @param value 要转换的值,可以是字符串数字或带有单位的字符串
  7. * @returns 转换后的数字,如果无法转换则返回0
  8. */
  9. // #ifndef UNI-APP-X && APP
  10. export function unitConvert(value : string | number, base: number = 0) : number {
  11. // 如果是字符串数字
  12. if (isNumeric(value)) {
  13. return Number(value);
  14. }
  15. // 如果有单位
  16. if (isString(value)) {
  17. const reg = /^-?([0-9]+)?([.]{1}[0-9]+){0,1}(em|rpx|px|%)$/g;
  18. const results = reg.exec(value);
  19. if (!value || !results) {
  20. return 0;
  21. }
  22. const unit = results[3];
  23. const _value = parseFloat(value);
  24. if (unit === 'rpx') {
  25. return uni.upx2px(_value);
  26. }
  27. if (unit === 'px') {
  28. return _value * 1;
  29. }
  30. if(unit == '%') {
  31. return _value / 100 * base
  32. }
  33. // 如果是其他单位,可以继续添加对应的转换逻辑
  34. }
  35. return 0;
  36. }
  37. // #endif
  38. // #ifdef UNI-APP-X && APP
  39. import { isNumber } from '../isNumber'
  40. export function unitConvert(value : any | null, base: number = 0) : number {
  41. if (isNumber(value)) {
  42. return value as number
  43. }
  44. // 如果是字符串数字
  45. if (isNumeric(value)) {
  46. return parseFloat(value as string);
  47. }
  48. // 如果有单位
  49. if (isString(value)) {
  50. const reg = /^-?([0-9]+)?([.]{1}[0-9]+){0,1}(em|rpx|px|%)$/g;
  51. const results = reg.exec(value as string);
  52. if (results == null) {
  53. return 0;
  54. }
  55. const unit = results[3];
  56. const _value = parseFloat(value);
  57. if (unit == 'rpx') {
  58. const { windowWidth } = uni.getWindowInfo()
  59. return windowWidth / 750 * _value;
  60. }
  61. if (unit == 'px') {
  62. return _value;
  63. }
  64. if(unit == '%') {
  65. return _value / 100 * base
  66. }
  67. // 如果是其他单位,可以继续添加对应的转换逻辑
  68. }
  69. return 0;
  70. }
  71. // #endif
  72. // 示例
  73. // console.log(unitConvert("123")); // 输出: 123 (字符串数字转换为数字)
  74. // console.log(unitConvert("3.14em")); // 输出: 0 (无法识别的单位)
  75. // console.log(unitConvert("20rpx")); // 输出: 根据具体情况而定 (根据单位进行转换)
  76. // console.log(unitConvert(10)); // 输出: 10 (数字不需要转换)