index.ts 2.0 KB

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