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.jquery.com/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.jquery.com/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.jquery.com/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
廣告