Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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') would return the correct width by using the declared style width (even if that value is different from the initial stylesheet). The problem is that the css('width') method returns a string, generally in a "100px" fashion. My question resolves into: how to retrieve the number from the "100px" string? Is there an easy way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
139 views
Welcome To Ask or Share your Answers For Others

1 Answer

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();
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...