我创建了一个插件来底部对齐元素。我以最简单的形式这样做了:
- 获取外层元素的高度 (DIV)
- 获取当前元素的高度
- 结果=outerHeight - 当前元素的高度
- sett CSS 属性 'top' = 结果。
它可以在 Firefox 和 IE8 中运行,但不能在 Opera 或 Google Chrome 中运行。
我猜这与边框、填充和边距有关。那么我需要做什么才能使其跨浏览器工作?
更新
代码已修改并正在运行。
(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">
<div class="floatLeft"> Variable content here </div>
<img class="bottomAlign floatRight" src="" /> </div>
</div>
并应用我的 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:absolute
。绝对定位的元素不占用空间,但需要位于具有位置的元素内部(即 position:relative
)
所以,直接使用 CSS:
.myOuterDiv { position: relative }
.bottomAlign { position: absolute; bottom: 0 }
但请注意,它曾经占据的任何位置(即由于向右浮动)都将不再占据。
关于jquery - 如何使用 jQuery 跨浏览器计算元素的高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2043321/