Cross Browser offsetWidth

蓝咒 提交于 2019-12-07 00:15:14

问题


I've been having an issue with using offsetWidth across different browsers. This difference in results is causing some strange layouts. I've created a very small example that displays what I'm seeing.

jsbin

HTML

<table id="tbl">
  <tr>
    <td>Cell 1</td>
    <td>Cell 2</td>
  </tr>
</table>
<button onclick="calc()">Calculate Offset Width</button>

<div>Cell 1 offsetWidth: <span id="c1offWidth"></span></div>

js

function calc(){
  document.getElementById('c1offWidth').innerHTML =
      document.getElementById('tbl').children[0].children[0].offsetWidth;
}

CSS

Erik Meyer's Reset CSS

When I run this on chrome, safari, and opera the value returned for Cell 1's offset width is 72. When I run this on firefox and IE9-10 the value returned is 77.

I was under the impression this was the best way to calculate the width of an element including padding and border.

Is there a cross browser solution that will always return the same result? I tried using jQuery but the results were even more confusing.

EDIT Because everyone is recommending outerWidth I made a jsbin for that also. The results still differ across browsers. Chrome returns 36; IE9-10 and Firefox return 39.

jsbin updated


回答1:


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.




回答2:


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




回答3:


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

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

See DEMO.




回答4:


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



来源:https://stackoverflow.com/questions/14990963/cross-browser-offsetwidth

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