UNPKG

t-comm

Version:

专业、稳定、纯粹的工具库

61 lines (59 loc) 1.51 kB
/** * 转化 rem 单位 * @param {string} content 输入内容 * @param {number} factor 转化比例,默认 100 * @param {string} unit 转化单位,默认 rpx * @returns {string} 转化后的结果 * * @example * ```ts * transFormRem('1.22rem') * // 122rpx * * transFormRem('1.22rem', 50, 'px') * // 61px * * transFormRem('.21rem', 50, 'px') * // 10.50px * ``` */ function transFormRem(content, factor, unit) { if (factor === void 0) { factor = 100; } if (unit === void 0) { unit = 'rpx'; } if (content == null) { return content; } var pattern = new RegExp('([0-9.]*[0-9]+)([\\s]*)(rem)', 'g'); var match = undefined; var records = []; // eslint-disable-next-line no-cond-assign while (match = pattern.exec(content)) { var keyword = match[0]; var number = parseFloat(match[1]); records.push({ index: match.index, length: keyword.length, keyword: keyword, number: number }); } if (records.length > 0) { var buffer = "".concat(content); for (var _i = 0, records_1 = records; _i < records_1.length; _i++) { var record = records_1[_i]; var number = (record.number * factor).toFixed(2); if (+number == parseInt(number, 10)) { // 去掉无效的小数点,比如:28.00 number = "".concat(parseInt(number, 10)); } buffer = buffer.replace(record.keyword, "".concat(number).concat(unit)); } return buffer; } return content; } export { transFormRem };