如何使用jQuery计算元素跨浏览器的高度?

我创建了一个插件来底部对齐元素。 在它最简单的forms我这样做:

  1. 获取outerElement(DIV)的高度
  2. 获取当前元素的高度
  3. result = outerHeight – 当前元素的高度
  4. 设置CSS属性’top’=结果。

它适用于Firefox和IE8,但不适用于Opera或Google Chrome。

我猜它与边框,填充和边距有关。 那么我需要做些什么才能让它跨浏览器工作呢?

UPDATE
代码已经修订,现在正在运行。

(function($){ $.fn.alignBottom = function() { var defaults = { outerHight: 0, elementHeight: 0 }; var options = $.extend(defaults, options); var bpHeight = 0; // Border + padding return this.each(function() { options.outerHight = $(this).parent().outerHeight(); bpHeight = options.outerHight - $(this).parent().height(); options.elementHeight = $(this).outerHeight(true) + bpHeight; $(this).css({'position':'relative','top':options.outerHight-(options.elementHeight)+'px'}); }); }; })(jQuery); 

HTML可能看起来像这样:

 div class="myOuterDiv"> 
Variable content here

并应用我的jQuery插件:

 jQuery(".bottomAlign").alignBottom(); 

您可能需要查看outerHeight() jQuery方法:

 options.outerHight = $(this).parent().outerHeight(); options.elementHeight = $(this).outerHeight( true ); // Include margins 

你也可能需要使用.position().top这是元素已经从包含元素的顶部移开的距离:

 var new_top = $(this).parent().outerHeight() - $(this).outerHeight() - $(this).position().top; 

另一种方法

关于position:relative的几件事position:relative 。 像这样定位的元素会占用空间,但可以向任何方向移动。 请注意,移动它们不会改变占用空间的位置,只会显示元素显示的位置。

关于position:absolute 。 绝对定位的元素不占用空间,但需要位于具有位置的元素内(即position:relative

所以,直接CSS:

 .myOuterDiv { position: relative } .bottomAlign { position: absolute; bottom: 0 } 

但请注意,它过去占据的任何位置(即由于浮动权利)将不再占用。

Interesting Posts