首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用jQuery计算跨浏览器元素的高度?

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

Stack Overflow用户
提问于 2010-01-11 16:52:25
回答 1查看 1.7K关注 0票数 2

我创建了一个插件来对齐一个元素。这是我最简单的做法:

  1. 获取outerElement (DIV)的高度(
  2. )获取当前元素的高度(
  3. result = outerHeight )--当前元素的高度(
  4. sett )属性'top‘=

而且效果很好..。在火狐和IE8中,但没有在Opera或Google中。

我猜这和边框,填充和毛边有关。那么,我要做什么才能使它跨浏览器工作呢?

更新

代码已经修改,现在正在工作。

代码语言:javascript
复制
(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看起来可能如下所示:

代码语言:javascript
复制
div class="myOuterDiv">
    <div class="floatLeft"> Variable content here </div>
    <img class="bottomAlign floatRight" src="" /> </div>
</div>

并应用我的jQuery插件:

代码语言:javascript
复制
jQuery(".bottomAlign").alignBottom();
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-01-11 17:04:10

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

代码语言:javascript
复制
options.outerHight = $(this).parent().outerHeight();
options.elementHeight = $(this).outerHeight( true ); // Include margins

您还可能需要使用.position().top,即元素已经从包含元素的顶部移开的距离:

代码语言:javascript
复制
var new_top = $(this).parent().outerHeight() - $(this).outerHeight() - $(this).position().top;

另一种方法

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

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

因此,在直接CSS中:

代码语言:javascript
复制
.myOuterDiv { position: relative }
.bottomAlign { position: absolute; bottom: 0 }

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2043321

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档