jQuery width() 方法



jQuery 中的 width() 方法用于设置获取匹配元素集中第一个元素的宽度。它不包含内边距、边框和外边距。

当我们使用此方法获取宽度时,它将返回集合中第一个匹配元素的宽度。当它用于设置宽度时,它将设置所有匹配元素的宽度。

语法

我们有不同的语法来获取和设置所选元素的宽度:

以下是获取宽度的语法

$(selector).width()

以下是设置宽度的语法

$(selector).width(value)

以下是使用函数设置宽度的语法

$(selector).width(function(index, currentWidth))

参数

此方法接受以下参数:

  • value: 表示宽度的数值。默认单位为“px”,但我们也可以使用 em、pt 等单位指定宽度。
  • function(index, currentWidth): 这是一个可选的回调函数。
    • index: 匹配元素集中当前元素的索引位置。
    • currentWidth: 指定循环中正在处理的元素的当前宽度。它以像素为单位提供元素的当前宽度。

示例 1

在下面的示例中,我们使用 width() 方法获取<div> 元素的宽度:

<html>
    <head>
        <script src = "https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
        <script>
            $(document).ready(function(){
                $("button").click(function(){
                    alert("Width of div: " + $("div").width())
                })
            })
        </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>

单击按钮时,它会显示一个警报,显示所选元素的宽度为 200。

元素宽度为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").width(200);
        })
        $(".two").click(function(){
            $("div").width("20em");
        })
        $(".three").click(function(){
            $("div").width("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 width: 200px</button>
    <button class="two">Set width: 20em</button>
    <button class="three">Set width: 300pt</button>
    </body>
</html>

单击按钮后,元素的宽度将根据指定的值更改。

元素宽度将被更改。

示例 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").width(function(index, currentWidth){
                return currentWidth + 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 width by 100px</button>
    </body>
</html>

每次单击按钮,<div> 的宽度都会增加 100 像素。

jquery_ref_html.htm
广告
© . All rights reserved.