cxc-szcx-uniapp/uni_modules/lime-shared/unitConvert/index.ts

80 lines
2.2 KiB
TypeScript
Raw Normal View History

2024-09-14 02:26:50 +00:00
// @ts-nocheck
import { isString } from '../isString'
import { isNumeric } from '../isNumeric'
/**
*
* @param value
* @returns 0
*/
2025-02-11 01:34:29 +00:00
// #ifndef UNI-APP-X && APP
export function unitConvert(value : string | number, base: number = 0) : number {
2024-09-14 02:26:50 +00:00
// 如果是字符串数字
if (isNumeric(value)) {
return Number(value);
}
// 如果有单位
if (isString(value)) {
const reg = /^-?([0-9]+)?([.]{1}[0-9]+){0,1}(em|rpx|px|%)$/g;
const results = reg.exec(value);
if (!value || !results) {
return 0;
}
const unit = results[3];
2025-02-11 01:34:29 +00:00
const _value = parseFloat(value);
2024-09-14 02:26:50 +00:00
if (unit === 'rpx') {
2025-02-11 01:34:29 +00:00
return uni.upx2px(_value);
2024-09-14 02:26:50 +00:00
}
if (unit === 'px') {
2025-02-11 01:34:29 +00:00
return _value * 1;
}
if(unit == '%') {
return _value / 100 * base
2024-09-14 02:26:50 +00:00
}
// 如果是其他单位,可以继续添加对应的转换逻辑
}
return 0;
}
// #endif
2025-02-11 01:34:29 +00:00
// #ifdef UNI-APP-X && APP
2024-09-14 02:26:50 +00:00
import { isNumber } from '../isNumber'
2025-02-11 01:34:29 +00:00
export function unitConvert(value : any | null, base: number = 0) : number {
2024-09-14 02:26:50 +00:00
if (isNumber(value)) {
return value as number
}
// 如果是字符串数字
if (isNumeric(value)) {
return parseFloat(value as string);
}
// 如果有单位
if (isString(value)) {
const reg = /^-?([0-9]+)?([.]{1}[0-9]+){0,1}(em|rpx|px|%)$/g;
const results = reg.exec(value as string);
if (results == null) {
return 0;
}
const unit = results[3];
2025-02-11 01:34:29 +00:00
const _value = parseFloat(value);
2024-09-14 02:26:50 +00:00
if (unit == 'rpx') {
2025-02-11 01:34:29 +00:00
// const { windowWidth } = uni.getWindowInfo()
// return windowWidth / 750 * _value;
return uni.rpx2px(_value)
2024-09-14 02:26:50 +00:00
}
if (unit == 'px') {
2025-02-11 01:34:29 +00:00
return _value;
}
if(unit == '%') {
return _value / 100 * base
2024-09-14 02:26:50 +00:00
}
// 如果是其他单位,可以继续添加对应的转换逻辑
}
return 0;
}
// #endif
// 示例
// console.log(unitConvert("123")); // 输出: 123 (字符串数字转换为数字)
// console.log(unitConvert("3.14em")); // 输出: 0 (无法识别的单位)
// console.log(unitConvert("20rpx")); // 输出: 根据具体情况而定 (根据单位进行转换)
// console.log(unitConvert(10)); // 输出: 10 (数字不需要转换)