Alright, I've search the jQuery docs (needs somebody devoted to maintaining), I've searched SO, and I've searched Google. I can't find the answer to this question.
In the past, I remember jQuery working like this:
$('#myObj').width()
returns the computed width of #myObj
.$('#myObj').css('width')
returns the width as it is entered into the CSS stylesheet.
Now, any jQuery package I use returns the exact same number no matter which method I use.
$('#myObj').width()
returns the computed width of #myObj
as an integer (float?).$('#myObj').css('width')
returns the computed width of #myObj
as a string with px
on the end.
#myobject{
width: 14em;
height: 14em;
}
<div id="myobject">Has Text</div>
<script type="text/javascript">
$( '#myobject' ).click(function(){
alert($(this).css('width') + "\n" + $(this).width());
});
</script>
//Always alerts "224px [newline] 224"
//Expected to alert "14em [newline] 224"
These pixel-based return values are almost completely useless, as I need to do calculations based on what's actually in the CSS. For example, I want to do math on the left
position of an element, but I can't because it keeps returning pixel values, which are worthless in an em
-based design.
Is there any way to get the actual values out of the CSS in jQuery?
Is this a jQuery bug, or am I missing something?
Here's a jsfiddle: http://jsfiddle.net/yAnFL/1/.
Apparently, this is the intended result.
I have decided to use this plugin to do conversions for me.
Taking away control of CSS seems like a poor choice in the jQuery design.
This is not a complete answer to your question but it may be a working solution to caclulate the em values. I adapted this function from here. And here is the updated fiddle.
$.fn.emWidth = function(){
var wpx = this.width();
var temp = $('<div />').css({
width:'1em',
position: 'absolute'
});
this.append(temp);
var oneEm = temp.width();
temp.remove();
var value = wpx/oneEm;
return Math.round(value*100)/100;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With