Libon

Increase string a value with unit

0Mins #CSS#math#JavaScript
使用带单位的 CSS 值进行数学运算
1
/**
2
* Increase string a value with unit
3
*
4
* @example '2px' + 1 = '3px'
5
* @example '15em' + (-2) = '13em'
6
*/
7
export function increaseWithUnit(target: number, delta: number): number
8
export function increaseWithUnit(target: string, delta: number): string
9
export function increaseWithUnit(target: string | number, delta: number): string | number
10
export function increaseWithUnit(target: string | number, delta: number): string | number {
9 collapsed lines
11
if (typeof target === 'number')
12
return target + delta
13
const value = target.match(/^-?[0-9]+\.?[0-9]*/)?.[0] || ''
14
const unit = target.slice(value.length)
15
const result = (parseFloat(value) + delta)
16
if (Number.isNaN(result))
17
return target
18
return result + unit
19
}

  1. VueUse Source

CD ..