jQuery innerWidth() 方法



jQuery 中的 innerWidth() 方法用於獲取匹配元素集中第一個匹配元素的內部寬度,包括內邊距,但不包括邊框或外邊距。

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

語法

以下是 jQuery 中 innerWidth() 元素的語法:

$(selector).innerWidth()

引數

此方法不接受任何引數。

示例 1

在此示例中,我們使用 innerWidth() 方法返回所選元素(在本例中為 <div> 元素)的內部寬度:

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                const innerWidth = $("#element").innerWidth();
                alert("Inner width of the element: " + innerWidth);
            });
        });
    </script>
</head>
<body>
    <div id="element" style="width: 200px; padding: 20px; border: 2px solid black; background-color: yellow;">
        This is a div element.
    </div>
    <button>Get Inner Width</button>
</body>
</html>

當我們點選按鈕時,它將觸發一個警報,顯示 <div> 元素的內部寬度。

示例 2

在此示例中,我們在匹配元素集中有多個 <div> 元素。因此,當觸發 innerWidth() 方法時,它會返回第一個匹配元素的內部寬度:

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                const innerWidth = $("#element").innerWidth();
                alert("Inner width of the first selected element: " + innerWidth);
            });
        });
    </script>
</head>
<body>
    <div id="element" style="width: 200px; padding: 20px; border: 2px solid black; background-color: yellow;">
        div element (width: 200px padding: 20px)
    </div>
    <div id="element" style="width: 250px; padding: 25px; border: 2px solid black; background-color: yellow;">
        div element (width: 250px padding: 25px)
    </div>
    <div id="element" style="width: 300px; padding: 30px; border: 2px solid black; background-color: yellow;">
        div element (width: 300px padding: 30px)
    </div>
    <button>Get Inner Width of first selected element.</button>
</body>
</html>

當我們點選按鈕時,它會給出匹配集中第一個選定的 <div> 元素的內部寬度。

jquery_ref_html.htm
廣告

© . All rights reserved.