@@ -2,7 +2,7 @@ import { arrayEach } from './array';
22import { easingFunctional , EasingName } from './easing' ;
33import { objectEach , objectMerge } from './object' ;
44import { stringKebabCase } from './string' ;
5- import { isObject } from './type' ;
5+ import { isObject , isString } from './type' ;
66
77export interface Style {
88 [ propName : string ] : string | number ;
@@ -179,3 +179,35 @@ export function getComputedCssVal(el: HTMLElement, property: string, reNumber: b
179179 const originVal = getComputedStyle ( el ) . getPropertyValue ( property ) ?? '' ;
180180 return reNumber ? Number ( originVal . replace ( / ( [ 0 - 9 ] * ) ( .* ) / g, '$1' ) ) : originVal ;
181181}
182+
183+ /**
184+ * 字符串的像素宽度
185+ * @param {string } str 目标字符串
186+ * @param {number } fontSize 字符串字体大小
187+ * @param {boolean } isRemoveDom 计算后是否移除中间dom元素
188+ * @returns {* }
189+ */
190+ export function getStrWidthPx ( str : string , fontSize : number = 14 , isRemoveDom : boolean = false ) : number {
191+ let strWidth = 0 ;
192+ console . assert ( isString ( str ) , `${ str } 不是有效的字符串` ) ;
193+ if ( isString ( str ) && str . length > 0 ) {
194+ let getEle : HTMLSpanElement | null = document . querySelector ( '#getStrWidth1494304949567' ) ;
195+ if ( ! getEle ) {
196+ const _ele = document . createElement ( 'span' ) ;
197+ _ele . id = 'getStrWidth1494304949567' ;
198+ _ele . style . fontSize = fontSize + 'px' ;
199+ _ele . style . whiteSpace = 'nowrap' ;
200+ _ele . style . visibility = 'hidden' ;
201+ _ele . textContent = str ;
202+ document . body . appendChild ( _ele ) ;
203+ getEle = _ele ;
204+ }
205+
206+ getEle ! . textContent = str ;
207+ strWidth = getEle ! . offsetWidth ;
208+ if ( isRemoveDom ) {
209+ document . body . appendChild ( getEle ) ;
210+ }
211+ }
212+ return strWidth ;
213+ }
0 commit comments