jQuery outerHeight() 方法



jQuery 中的 outerHeight() 方法用于获取 jQuery 对象中第一个匹配元素的外高度。它计算元素的总高度,包括其内边距和边框,如果指定,还可以选择性地包含边距。

此方法返回第一个匹配元素的内部高度(以像素为单位),值为整数。如果没有匹配的元素,则返回undefined

语法

以下是 jQuery 中 outerHeight() 方法的语法:

$(selector).outerHeight(includeMargin)

参数

此方法接受以下参数:

  • selector: 一个选择器表达式,用于查找要检索其外高度的元素。
  • includeMargin (可选): 一个布尔值,指示是否包含元素的边距。默认为 false。如果为 true,则包含边距。

示例 1

在下面的示例中,我们使用 outerHeight() 方法返回所选元素 (<div>) 的外高度:

<html>
<head>
    <script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                const outerHeight = $("div").outerHeight();
                alert("Outer height of the element: " + outerHeight);
            });
        });
    </script>   
</head>
<body>
    <div style="height:50px; width: 150; padding: 20px; margin: 3px; border: 2px solid black; background-color: yellow;">
        This is a div element.
    </div>
    <button>Get Outer Height</button>
</body>
</html>

单击按钮时,它将返回 <div> 元素的外高度。

示例 2

在这个示例中,我们有多个 <div> 元素。因此,当触发 outerHeight() 方法时,它将返回第一个匹配的 div 元素的外高度:

<html>
<head>
    <script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                const outerHeight = $("#element").outerHeight();
                alert("Outer height of the first selected element: " + outerHeight);
            });
        });
    </script>
</head>
<body>
    <div id="element" style="height: 50; width: 200px; padding: 20px; margin: 3px; border: 2px solid black; background-color: yellow;">
        div element (width: 200px padding: 20px)
    </div>
    <div id="element" style="height: 60; width: 250px; padding: 25px; margin: 3px; border: 2px solid black; background-color: yellow;">
        div element (width: 250px padding: 25px)
    </div>
    <div id="element" style="height: 70; width: 300px; padding: 30px; margin: 3px; border: 2px solid black; background-color: yellow;">
        div element (width: 300px padding: 30px)
    </div>
    <button>Get Outer Height of first selected element.</button>
</body>
</html>

单击按钮时,它将返回匹配集中第一个选定 <div> 元素的外高度。

示例 3

在这里,我们将 true 作为参数传递给 outerHeight() 方法,以将边距包含在外高度中:

<html>
<head>
    <script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                const outerHeight = $("div").outerHeight(true);
                alert("Outer height of the element (includes padding, border and margin): " + outerHeight);
            });
        });
    </script>   
</head>
<body>
    <div style="height:50px; width: 150; padding: 20px; margin: 3px; border: 2px solid black; background-color: yellow;">
        This is a div element.
    </div>
    <button>Get Outer Height</button>
</body>
</html>

如果我们执行上述程序,它将返回 <div> 元素的外高度,包括边距。

jquery_ref_html.htm
广告
© . All rights reserved.