Convert css width string to regular number

后端 未结 5 811
闹比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:19

    I would stick to .width() because it actually gets the computed width instead of css width. Instead of hiding it with .hide() (display: none) you could hide it with .css('visible', 'hidden') then .width() should work.

    from my comment If you don't want to change your .hide()´s then you could apply visible: hidden and thereafter .show() and then measure the height. After you have measured it, reverse that. Objects still affects the page layout when they are hidden by visible: hidden - beware of that.

    To avoid tags which mess with the layout, you could set the position to absolute, move it to the body tag and then measure.

    0 讨论(0)
  • 2020-12-15 18:29

    In plain JavaScript:

    parseInt('100px', 10)
    

    Works with "100em", "100%", and even with: "100". No need for any Regular Expression patterns.

    0 讨论(0)
  • 2020-12-15 18:29

    Oh, I came up with:
    new Number($elem.css('width').slice(0, -2));
    //to extract the 'px' and return a regular number

    Now I only hope that jquery allways returns the same string fashion: "100px"

    0 讨论(0)
  • 2020-12-15 18:38

    If it always returns in px format, "100px", "50px" etc (i.e. not "em" or percent), you could just...

    var width = parseInt($("#myelem").css("width"),10); // always use a radix
    

    or

    var width = parseInt(element.style.width,10); // always use a radix
    

    It ignores the "px" suffix so you should be good to go.

    Although deep down I'm thinking that something isn't right if $("#myelem").width() isn't working.

    Note on hidden elements.

    If you are adding jQuery to progressively enhance you page, the element you are calculating should be visible when the page first loads. So you should get the width before you initially hide the element. By doing this, $("#myelem").width() will work.

    var myWidth = 0;
    
    $(document).ready( function () {
        myWidth = $("#myelem").width();
        $("#myelem").hide();
    });
    
    0 讨论(0)
  • 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, ''));
    
    0 讨论(0)
提交回复
热议问题