跨浏览器offsetWidth [英] Cross Browser offsetWidth

查看:154
本文介绍了跨浏览器offsetWidth的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用offsetWidth时遇到了跨越不同浏览器的问题。结果的这种差异导致一些奇怪的布局。我创建了一个非常小的例子,显示我看到的。

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的重置CSS

当我在chrome,safari和opera上运行时,对Cell 1的偏移宽度返回的值是72.当我在firefox和IE9-10上运行时,返回的值是77。

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.

是否有跨浏览器解决方案将始终返回相同的结果?我尝试使用jQuery,但结果是更混乱。

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

编辑
因为每个人都推荐outerWidth我做了一个jsbin也。不同浏览器的结果仍然不同。 Chrome返回36; IE9-10和Firefox会返回39.

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已更新

推荐答案

由于您使用jQuery标记的帖子,我假设一个jQuery解决方案是可以接受的。 outerWidth() 有什么问题?

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

例如:

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

使用jQuery为表格带来了许多优点上面需要减少的代码量)。您还应该考虑使用非介入式事件处理程序。例如,从按钮中删除​​ onclick 属性,然后执行以下操作:

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

请参阅 jsFiddle demo

这篇关于跨浏览器offsetWidth的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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