Javascript / jQuery: .css pixel values

I just realized that there is a difference between

<foo>.css('marginTop') 

(which I thought was standard jquery notation) and

 <foo>.css('margin-top') 

(which I considered non-standard).

If has margin-top: 3em; (for example), the first notation gives me 3em, the second notation gives me 48px (which is 3em in pixels). I like this behavior, but I could not find anything about it in the API (or am I blind?)

Why is this and where can I find information about it?

PS: To be precise: of course, other attributes besides working with the brand up, as well as ...

Thanks!

+4
source share
2 answers

Doc says that "jQuery can interpret CSS and DOM formatting the properties of multiple words in the same way," but in fact he does it through crude and ready-made hacks that don't always behave predictably.

In particular, if you specify the camelCaseName DOM style, it will first try to access the inline style declaration as style.camelCaseName . Then, if this fails (usually because the style was not set in the string), it returns to trying to getComputedStyle with camelCaseName converted to hyphen-separated-name (*). A calculated style is not the same as a declared style: the browser can allow various relative declarations in the calculated style, for example, converting lengths to pixel units.

However, the opposite is not true! If you specify a hyphen-separated-name CSS style, it will go straight into the computed style code (*) without trying to convert it to camelCaseName and look at the inline style.

I don’t think I would like to rely on this behavior ... it smells a little to me. If you can keep the inline style declaration from the element you want to measure, you must be sure that you will always get the calculated style no matter what type of name you use. But then again, jQuery does not give you this as a documented promise. This is the nature of the attempt to hide the complex model behind the seemingly simple β€œDo What I Mean” interface.

(*): except IE, where there is no getComputedStyle function, so it goes back to the weird and fragile combination of currentStyle , runtimeStyle and document changes to try to get a computed style.

+6
source

The difference is with CSS and JavaScript being the same thing. This would not be in the jQuery API, but in the CSS link.

CSS uses margin-top, and JavaScript uses marginTop for the same thing. The default value in CSS (margin-top) is 0px. So you get 48px instead of 3em.

See http://www.w3schools.com/css/css_reference.asp for more details.

+1
source

Source: https://habr.com/ru/post/1301022/


All Articles