首页 » Web技术 » JS/jQuery » 正文

jQuery中.outerHeight()与.outerWidth()函数详解

outerHeight()/outerHeight()函数用于设置或返回当前匹配元素的外高/宽度

外高/宽度默认包括元素的内边距(padding)、边框(border),但不包括外边距(margin)部分的高/宽度。你也可以指定参数为true,来包括外边距(margin)部分的高/宽度。如下图:


jQuery.outerHeight()

如果你要获取其它情况的高/宽度,请使用 height()/width() 和 innerHeight()/innerWidth() 。

该函数属于jQuery对象(实例),并且对不可见的元素依然有效。

语法

jQuery 1.2.6 新增该函数。

.outerHeight( [includeMargin ] )

.outerWidth( [includeMargin ] )
注意:如果当前jQuery对象匹配多个元素,则只返回第一个匹配的元素的外高/宽度。

参数

includeMargin(Boolean类型/可选):指定是否把margin计算在内,默认为false

当参数为空或者false时,会计算paddingborder值;而当参数为true时,还会把margin值计算在内。

注:这两个方法不适用于windowdocument对象,应该用height()width()方法来代替。

返回值

返回第一个匹配元素的外高/宽度。当匹配多个元素时,以其中第一个匹配到的元素为准。

补充说明:

  • 尺寸相关的API的返回值,包括.outerHeight().outerWidth(),某些情况下可能是小数,你的代码不能直接把它们当作整数用。当页面被用户缩放之后,返回的值可能也是不正确的,浏览器并没有提供相应的API来检测浏览器缩放状态。
  • 当元素的父元素是hidden的时候,返回值有可能是不正确的。为了得到准确的值,在使用这两个函数前,请先让父元素显示。

示例

此处以 .outerHeitht() 为例,.outerWidth()方法类似

<div class="container">
    <div id="example1" style="width: 100px;height: 100px;margin: 5px;padding: 10px;border: 2px solid #ddd">Example 1</div>
    <div id="example2" style="width: 100px;height: 100px;background: red;">Example 2</div>

</div>
<div id="result"><p>结果:</p></div>
<script type="text/javascript">
    var $result = $('#result'),
        $e1 = $('#example1'),
        $e2 = $('#example2'),
        $div = $('.container div');

    // outerHeitht() = height(100) + padding(10*2) + border(2*2) = 124
    $result.append('<p>$e1.outerHeight():'+$e1.outerHeight()+'</p>');
    $result.append('<p>$e2.outerHeight():'+$e2.outerHeight()+'</p>');
    
    //返回匹配到的第一个元素的结果
    $result.append('<p>$div.outerHeight():'+$div.outerHeight()+'</p>');
    
    // outerHeight(true) = height(100) + padding(10*2) + margin(5*2) + border(2*2) = 134
    $result.append('<p>$e1.outerHeight(true):'+$e1.outerHeight(true)+'</p>');
    $result.append('<p>$e2.outerHeight(true):'+$e2.outerHeight(true)+'</p>');
</script>

运行结果截图:

outerHeight-result

发表评论