Why does jQuery.css('width') return differ

2020-04-08 14:46发布

问题:

I've written some jQuery code that reads the width of the columns in a table and applies them to another table.

On my page, there is a TABLE like this:

<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've written 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 the code runs, I would expect colWidths to be [100, 40], and in FireFox, it is. However, in IE8, it is [92,32]. This breaks my page in IE that depends on the values being correct.

I believe that it may be pertinent that my table is contained within a jQuery-ui-tabs element, and I know that the jQuery-ui css can do weird things, so I wouldn't be surprised if this has something to do with it.

Why is it that jQuery.css('width') doesn't return the value I expect in IE8? What can I do about it?

回答1:

JQuery normalizes browser handling in this situation via $().width().

css("width") is a different attribute / property that is not normalized but instead it retrieves the CSS value for the element(s). width() is the "actual size in the dom" but doesn't take padding and margins where applicable into consideration where css("width") only retrieves the CSS value. As others have mentioned below this answer, .outerWidth() will do what .width() accomplishes, but includes padding and margins as represented by the native browser.

In short:

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

A good parallel example is this:

$(this).css("width")

is closer to

$(this).attr("name")

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

Edit:

Here is something I just tabbed over and saw that also illustrates the difference:

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

The alert will be a numeric value (pixels).



回答2:

I faced the same problem trying to detect the width of the body and load specific scripts and I worked around it this way. May help you as well.

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

this gives a consistent value in all major browsers

`