Convert css width string to regular number

后端 未结 5 812
闹比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: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();
    });
    

提交回复
热议问题