Javascript/Jquery: .css pixel-values
I just realised there is a difference between
<foo>.css('marginTop')
(which I thought is the standard jquery-notation) and
<foo>.css('margin-top')
(which I thought was non-standard).
If has margin-top: 3em; (for example), the first notation gives 开发者_Python百科me 3em, the second notation gives me 48px (which is 3em in Pixels). I like this behaviour but I could not find anything about it in the API (or am I blind?)
Why is this the case and where can I find information about it?
P.S.: Just to be precise: of course other attributes but margin-top work aswell...
Thank you!
The doc says “jQuery can equally interpret the CSS and DOM formatting of multiple-word properties”, but in reality it is doing that through rough and ready hacks which don't always behave predictably.
In particular, if you supply a DOM-style camelCaseName
, it will first try to access the inline style declaration as style.camelCaseName
. Then if that fails (typically because the style was not set inline), it falls back to trying getComputedStyle
with the camelCaseName
converted to hyphen-separated-name
(*). The computed style is not the same thing as the declared style: the browser can resolve various relative declarations in a computed style, such as converting lengths to pixel units.
However, the reverse does not hold! If you supply a CSS-style hyphen-separated-name
, it jumps straight to the computed style(*) code without trying to convert to camelCaseName
and look at the inline style.
I don't think I'd want to rely on this behaviour... it smells a little bit buggy to me. If you can keep the inline style declaration off the element you want to measure, you should be able to ensure you always get the computed style back regardless of which name type you use. But then again, jQuery doesn't give you that as a documented promise. Such is the nature of trying to hide a complicated model behind a seemingly-simple “Do What I Mean” interface.
(*): except in IE where there is no getComputedStyle
function, so it falls back to a weird and fragile mix of currentStyle
, runtimeStyle
and document alteration to try to get a computed style out.
The difference is related to CSS and JavaScript notation of the same thing. It would not be in the jQuery API but in a CSS reference.
CSS uses the margin-top while JavaScript uses the marginTop for the same thing. The default value in CSS (margin-top) is 0px. Therefore you get the 48px instead of the 3em.
See http://www.w3schools.com/css/css_reference.asp for more info.
精彩评论