jQuery outerHeight() 方法



jQuery 中的 outerHeight() 方法用於獲取 jQuery 物件中第一個匹配元素的外高度。它計算元素的總高度,包括其內邊距和邊框,如果指定,還可以選擇性地包含邊距。

此方法返回第一個匹配元素的內部高度(以畫素為單位),值為整數。如果沒有匹配的元素,則返回undefined

語法

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

$(selector).outerHeight(includeMargin)

引數

此方法接受以下引數:

  • selector: 一個選擇器表示式,用於查詢要檢索其外高度的元素。
  • includeMargin (可選): 一個布林值,指示是否包含元素的邊距。預設為 false。如果為 true,則包含邊距。

示例 1

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

<html>
<head>
    <script src="https://code.jquery.com/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.jquery.com/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.jquery.com/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
廣告