Why does jQuery.css ('width') return different values ​​in different browsers?

I wrote jQuery code that reads the width of columns in a table and applies them to another table.

On my page there is a TABLE:

<table style='table-layout:fixed;'> <tbody id='myTableBody'> <tr> <td style='width:100px;'>foo</td> <td style='width: 40px;'>bar</td> </tr> </tbody> </table> 

I wrote the following jQuery code to read the css width properties of this table:

 var colWidths = []; var cells = $('#myTableBody').find('td'); for (i = 0; i < cells.length; i++) colWidths.push($(cells[i]).css('width')); 

After running the code, I expect colWidths be [100, 40] , and in FireFox it is. However, in IE8 it is [92,32] . This breaks my page in IE, which depends on the correctness of the values.

I believe it might be appropriate that my table is contained in the jQuery-ui-tabs element, and I know that jQuery-ui css can do strange things, so I won’t be surprised if this has something to do with it.

Why doesn't jQuery.css ('width') return the value I expect in IE8? What can i do with this?

+4
source share
2 answers

JQuery normalizes browser processing in this situation through $().width() .

css("width") is another attribute / property that is not normalized, but instead retrieves the CSS value for the element (s). width() is the "actual size in dom", but it doesn't take into account the padding and the fields where css("width") retrieves only the CSS value. As mentioned below, the answer .outerWidth() will accomplish what .width() does, but includes padding and margins represented by its own browser.

In short:

 $(this).width() != $(this).css("width") 

A good parallel example is the following:

 $(this).css("width") 

closer to

 $(this).attr("name") 

than $(this).width() or $(this).height() .

Edit:

Here is what I just laid down and saw, which also illustrates the difference:

 $(this).css("height", "auto"); alert($(this).height()); 

The warning will be a numerical value (pixels).

+7
source

I ran into the same problem trying to determine the width of the body and load certain scripts, and I worked around it that way. Can help you.

 $('body,html').css({'overflow':'hidden'}); var width = $('body').width(); $('body,html').css({'overflow':''}); 

this gives consistent meaning in all major browsers

`

+1
source

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


All Articles