合同小程序前端代码仓库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
2.2 KiB

  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 | null | undefined, 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. return uni.rpx2px(_value)
  61. }
  62. if (unit == 'px') {
  63. return _value;
  64. }
  65. if(unit == '%') {
  66. return _value / 100 * base
  67. }
  68. // 如果是其他单位,可以继续添加对应的转换逻辑
  69. }
  70. return 0;
  71. }
  72. // #endif
  73. // 示例
  74. // console.log(unitConvert("123")); // 输出: 123 (字符串数字转换为数字)
  75. // console.log(unitConvert("3.14em")); // 输出: 0 (无法识别的单位)
  76. // console.log(unitConvert("20rpx")); // 输出: 根据具体情况而定 (根据单位进行转换)
  77. // console.log(unitConvert(10)); // 输出: 10 (数字不需要转换)