jQuery 中的 resize() 方法

resize() 方法是 jQuery 中的一个内置函数,用于在浏览器窗口改变大小时使用。本教程演示了如何在 jQuery 中使用 resize() 方法。

在 jQuery 中使用 resize() 方法

resize() 方法的工作方式类似于 JavaScript 的 onresize() 方法。它们用于调整窗口大小。

resize() 方法的语法是:

$(selector).resize(function)

selector 可以是窗口。而 function 是一个可选参数,将在调用 resize() 方法时被调用;这个函数也称为处理程序。

处理程序中的代码永远不应基于调用处理程序的次数,因为此事件可以连续发送,直到正在进行调整大小。此方法的返回值是具有调整大小属性的选定元素。

这里还应该提到 resize() 方法是 on("resize", handler) 的 jQuery 版本。因此,与此类似,可以使用 .off("resize") 方法进行分离。

让我们尝试一个例子:

<!DOCTYPE html>
<html>
<head>
    <title> jQuery resize() method </title>
    <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script>
    <script>
        var x = 0;
        $(document).ready(function(){
            $(window).resize(function(){
                $("span").text(x += 1);
                var Window_Size = "Width = " + $(window).width() + "<br/>Height = " + $(window).height();
                $('#DemoParagraph').html(Window_Size);
            });
        });
    </script>
    <style>
        span {
        font-weight: bold;
        color: blue;
        font-size: 30px;
        }
    </style>
</head>
<body>
    <h2> jQuery resize() method </h2>
    <p> Resize your browser's window and see the Resize() method effect. </p>
    <p> You have resized the window <span> 0 </span> times.</p>
    <p id = "DemoParagraph"> </p>
</body>
</html>

上面的代码使用 resize() 方法在调整大小时显示窗口的宽度和高度。见输出:

jQuery 中的 resize() 方法