jQuery height() 方法



jQuery 中的 height() 方法用於設定或獲取匹配元素集中第一個元素的高度。它不包括內邊距、邊框和外邊距。

當我們使用此方法獲取高度時,它會返回集合中第一個匹配元素的高度。當它用於設定高度時,它會設定所有匹配元素的高度。

語法

我們有不同的語法來獲取和設定所選元素的寬度 -

以下是 獲取 寬度 的語法

$(selector).height()

以下是 設定 寬度 的語法

$(selector).height(value)

以下是使用 函式 設定寬度的語法

$(selector).height(function(index, currentheight))

引數

此方法接受以下引數 -

  • value: 表示高度的數值。預設單位為“px”,但我們也可以指定 em、pt 等。
  • function(index, currentheight): 這是一個可選的回撥函式。
    • index: 匹配元素集中當前元素的索引位置。
    • currentheight: 它指定迴圈中正在處理的元素的當前高度。它以畫素為單位提供元素的當前高度。

示例 1

在以下示例中,我們使用 height() 方法獲取 <div> 元素的高度 -

<html>
    <head>
        <script src = "https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <script>
            $(document).ready(function(){
                $("button").click(function(){
                    alert("Height of div: " + $("div").height())
                })
            })
        </script>
    </head>
    <body>
        <div style="width: 200px; height: 50px; border: 1px solid black; background-color: yellow;">
            This is a div element.
        </div>
        <button>Click</button>
    </body>
</html>

當我們點選按鈕時,它會彈出一個警報,顯示所選 <div> 元素的高度為 200。

示例 2

在此示例中,我們使用不同的單位(如 px、em 和 pt)設定 <div> 元素的高度 -

<html>
<head>
<script src = "https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(document).ready(function(){
        $(".one").click(function(){
            $("div").height(200);
        })
        $(".two").click(function(){
            $("div").height("20em");
        })
        $(".three").click(function(){
            $("div").height("300pt");
        })
    });
</script>
</head>
<body>
    <div style="width: 150px; height: 50px; border: 1px solid black; background-color: yellow;">
        This is a div element.
    </div>
    <button class="one">Set height: 200px</button>
    <button class="two">Set height: 20em</button>
    <button class="three">Set height: 300pt</button>
    </body>
</html>

單擊按鈕後,<div> 元素的高度將按指定更改。

示例 3

在這裡,我們使用可選的函式引數來增加 <div> 元素的高度 -

<html>
<head>
<script src = "https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(document).ready(function(){
        $(".one").click(function(){
            $("div").height(function(index, currentheight){
                return currentheight + 100;
            });
        })
    });
</script>
</head>
<body>
    <div style="width: 150px; height: 30px; border: 1px solid black; background-color: yellow;">
        This is a div element.
    </div>
    <button class="one">Increase the height by 100px</button>
    </body>
</html>

每次點選按鈕,<div> 的高度都會增加 100 畫素。

jquery_ref_html.htm
廣告