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

时间:2010-01-11 16:52:25

标签: jquery

我创建了一个底部对齐元素的插件。以最简单的形式,我做到了这一点:

  1. 获取outerElement(DIV)的高度
  2. 获取当前元素的高度
  3. result = outerHeight - 当前元素的高度
  4. 设置CSS属性'top'=结果。
  5. 它适用于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();
    

1 个答案:

答案 0 :(得分:1)

您可能需要查看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 }

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