为什么jQuery.css('width')在不同的浏览器中返回不同的值? [英] Why does jQuery.css('width') return different values in different browsers?

查看:269
本文介绍了为什么jQuery.css('width')在不同的浏览器中返回不同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一些jQuery代码,读取表中列的宽度并将它们应用到另一个表。

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

在我的页面上,有一个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>

我写了以下jQuery代码来读取此表的css宽度属性:

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'));

代码运行后,我会看到 colWidths [100,40] ,而在FireFox中,它是。然而,在IE8中,它是 [92,32] 。这打破了我在IE中的页面,这取决于值是否正确。

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.

我相信我的表格包含在一个jQuery-ui-tabs元素内,我知道jQuery-ui css可以做奇怪的事情,所以我不会惊讶,如果这与它有关系。

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.

为什么是jQuery .css('width')不返回我在IE8期望的值?

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

推荐答案

JQuery通过 $()在这种情况下规范化浏览器处理。 width()

css(width)属性不是标准化的,而是检索元素的CSS值。 width()是dom中的实际大小,但在适用的情况下不会考虑填充和边距, css(width) 只检索CSS值。正如其他人在下面提到的这个答案, .outerWidth()将做 .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.

简而言之:

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

$ b b

一个很好的例子是:

A good parallel example is this:

$(this).css("width")

更接近

$(this).attr("name")

$ c> $(this).width()或 $(this).height()

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

编辑

这里是我刚刚选择的地方,看到的也说明了区别:

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).

这篇关于为什么jQuery.css('width')在不同的浏览器中返回不同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆