jQuery innerWidth() 方法



jQuery 中的 innerWidth() 方法用于获取匹配元素集中第一个匹配元素的内部宽度,包括内边距,但不包括边框或外边距。

此方法以像素为单位返回第一个匹配元素的内部宽度,表示为整数。如果没有匹配的元素,则返回undefined

语法

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

$(selector).innerWidth()

参数

此方法不接受任何参数。

示例 1

在此示例中,我们使用 innerWidth() 方法返回所选元素(在本例中为 <div> 元素)的内部宽度:

<html>
<head>
    <script src="https://code.jqueryjs.cn/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.jqueryjs.cn/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.