简体   繁体   中英

jQuery .css() returning pixels instead of percent

Alright, so when I get a CSS property that's been stored as a percent using jQuery .css() it is returned with its pixel value. This is great for my purposes actually, I can use it...is it an intended result I will see consistently in all modern browsers both now and in the future, though?

I can't seem to find much info here. Thanks!

From jQuery doc

The .css() method is a convenient way to get a style property from the first matched element, especially in light of the different ways browsers access most of those properties (the getComputedStyle() method in standards-based browsers versus the currentStyle and runtimeStyle properties in Internet Explorer) and the different terms browsers use for certain properties.

yes it is an intended result

if you want to find the actual style value , you can do something like this,

var topValue = $("#mydiv")[0].style.top

Yes, you can see this behaviour in all browsers both now and in future. Because this is how browsers render the css property . Scripting languages will get these details from the DOM after it got interpreted from the browser. So this is the natural behaviour and this wont change.

Additionally, Percentages will be converted into pixels based on the element's parent during rendering process. So that it will not display the css property in percentage while you retrieving that. You have to calculate it manually if you need it for sure.

This is covered by the burgeoning CSSOM specification . In general, yes, you can rely on pixel values provided the display property is not set to none . Section 9 of the above has the details; for most properties where you'd expect a number ( width and such), it says:

If the property applies to the element or pseudo-element and the resolved value of the 'display' property is not 'none', the resolved value is the used value. Otherwise the resolved value is the computed value.

...where "resolved value" means (for these properties) a number of pixels rather than a relative amount (percentage and similar), which would be the "computed value" ("computed" as in "taking all style rules into consideration").

Supporting the case of this being (newly) specified behavior, when non-pixel values have been returned in various situations, bugs have been reported and accepted (in WebKit , in jQuery , in YUI ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM