CSS height return using jQuery, not computed but declared

I think it could be the default in a previous version of jquery, but when I call .css("height") and .height() , it returns the calculated height, which I don't want - I only need the height value if it is specifically declared in the CSS file for this element.

As if it had not been declared anywhere, perhaps it could return 'auto' , as it does on the top and left, sometimes ...

For example, my CSS looks like this:

 .element{ margin-left:5px; color:red; } 

.css("margin-left") returns "5px" , and .css("height") returns 20 , although it is not specifically set ...

thanks

+6
source share
1 answer

The browser automatically calculates the height and width of the CSS.

You can see them, for example, on the "Calculated Styles" tab in Chrome Developer Tools (F12)

And the documents:

jQuery.width ()

Get the current calculated width for the first element in the set of matched elements, or set the width of each matched element.

The difference between .css (width) and .width () is that the latter returns a pixel value without a unit (e.g. 400), and the former returns a value with intact units (e.g. 400px)

But if you want to get the correct CSS value, I can advise against using jQuery

if we have HTML:

 <div id="elem" style="height: auto"></div> 

we can write js:

 $('#elem').get(0).style.height // "auto" 

if we have HTML:

 <div id="elem"></div> 

JS:

 $('#elem').get(0).style.height // "" 

universal function:

 var height = function(elem){ return $(elem).get(0).style.height === "" ? $(elem).height() : $(elem).get(0).style.height; } 
0
source

All Articles