Cross Browser offsetWidth

帅比萌擦擦* 提交于 2019-12-05 05:00:35

Since you tagged the post with jQuery, I assume that a jQuery solution is acceptable. What's wrong with outerWidth()?

For example:

function calc()
{
    var the_width = $('#tbl tr:eq(0) td:eq(0)').outerWidth();
    $('#c1offWidth').html(the_width);   
}

Using jQuery brings a number of advantages to the table (as you can see by the reduced amount of code needed above). You should also consider using non-intrusive event handlers, too. For example, remove the onclick attribute from your button, and do this:

$(function() {  
    $('button').click(function() {  
        var the_width = $('#tbl tr:eq(0) td:eq(0)').outerWidth();
        $('#c1offWidth').html(the_width);  
    });
});

Please see the jsFiddle demo.

The actual problem in your example was in that different browsers use different default fonts for rendering. And box-sizing for your cells is defined by content. If you set definite width for the element (as correctly stated in one of the comment) you'll get the definite and equal result.

ps: can't post comments...

offsetWidth is not reliable cross-browser. I would recommend using jQuery's outerWidth() instead.

$("#your-element").outerWidth();

See DEMO.

You can use jQuery's .outerWidth() if you need to get a cross-browser calculated width including things like borders and margin.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!