开发者

Cross-browser method for getting width and height of a DIV?

I use jQuery. I'm trying to find a way to get the current width and height of a DIV element, even if they're set to "auto". I've found many ways to do this, but no method returns the same width in IE. It is important that this method is cross-browser, as it will break the layout of the page if different numbers are returned in different browsers.

.width() and .height() do not work because in IE, padding is subtracted (e.g. width() returns 25 where width is 30 and padding is 5).

.outerWidth() and .outerHeight() are not consistent either. While they work IE (believe it or not) in FF, the p开发者_StackOverflow中文版adding is added again to the full width (e.g. outerWidth() returns 110 in FF where width is 100px and padding is 10px).

Is there any way out of this mess without writing complex browser checks? Thanks!


It sounds to me that you need to add a DOCTYPE to your page to force IE into "standards compliant" rather than "quirks" mode. See Quirks mode and strict mode.

Also see width():

Cross-browser method for getting width and height of a DIV?

and outerWidth():

Cross-browser method for getting width and height of a DIV?


I don't know whether this helps, but the following fragment will set the height of an inner element so that it completely fills the available space. The inner element (e) can be nested at any depth inside a reference element (r) which has a set height. The fragment takes into account the heights of all siblings between e and r. Both parameters can be passed either as DOM elements or JQuery objects.


var fit_v = function ( e, r, no_set ){
    if (!e.jquery) e = $(e);
    if (!r.jquery) r = $(r);
    var h, s, b = 0, d = 0;
    for (var i = 0; i < r[0].childNodes.length; i++){
      s = $(r[0].childNodes[i])
      d += s.outerHeight();
      d += Math.max(b,parseInt(s.css('margin-top')));
      b = parseInt(s.css('margin-bottom')); 
    } 
    d += b;
    h = r.height() - d;
    if (!no_set) e.height(h); 
    return h;
  };

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜