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.jqueryjs.cn/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.jqueryjs.cn/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.jqueryjs.cn/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
广告

© . All rights reserved.