Convert css width string to regular number

后端 未结 5 813
闹比i
闹比i 2020-12-15 18:11

While trying to compute the width of an hidden element I found that jquery.width() returns 0 for that elements\' width.

I found out that using jquery.css(\'width\'

5条回答
  •  感情败类
    2020-12-15 18:40

    You could remove non-numericals with a regular expression and then just convert to a number. This works no matter how you define the width (px, em, %, pt). Preserves decimal points too.

    vanilla javascript

    Number(elem.style.width.replace(/[^\d\.\-]/g, ''));
    

    jQuery

    Number($elem.css('width').replace(/[^\d\.\-]/g, ''));
    

提交回复
热议问题