Convert css width string to regular number
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?
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();
});
In plain JavaScript:
parseInt('100px', 10)
Works with "100em", "100%", and even with: "100". No need for any Regular Expression patterns.
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, ''));
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"
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.
精彩评论