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

查看:142
本文介绍了为什么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.

在我的页面上,有一个这样的表:

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()标准化浏览器处理.

JQuery normalizes browser handling in this situation via $().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")

一个很好的并行示例是这样:

A good parallel example is this:

$(this).css("width")

更接近

$(this).attr("name")

$(this).width()$(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(&amp;#39; width&amp;#39;)在不同的浏览器中返回不同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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