jQuery 调整窗口大小时调用函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15205609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:35:49  来源:igfitidea点击:

Call a function when window is resized

javascriptjquerywindow-resize

提问by Rich

How can I call for this(or any) JS function to be run again whenever the Browser window is resized?

每当调整浏览器窗口大小时,如何调用此(或任何)JS 函数再次运行?

<script type="text/javascript">
 function setEqualHeight(e) {
     var t = 0;
     e.each(function () {
         currentHeight = $(this).height();
         if (currentHeight > t) {
             t = currentHeight
         }
     });
     e.height(t)
 }
 $(document).ready(function () {
     setEqualHeight($(".border"))
 })
</script>

回答by udidu

You can use the window onresizeevent:

您可以使用窗口onresize事件:

window.onresize = setEqualHeight;

回答by dougajmcdonald

You can subscribe to the window.onresizeevent (See here)

您可以订阅该window.onresize事件(请参阅此处

window.onresize = setEqualHeight;

or

或者

window.addEventListener('resize', setEqualHeight);

回答by Merec

This piece of code will add a timer which calls the resize function after 200 milliseconds after the window has been resized. This will reduce the calls of the method.

这段代码将添加一个计时器,该计时器在调整窗口大小后 200 毫秒后调用调整大小函数。这将减少方法的调用。

var globalResizeTimer = null;

$(window).resize(function() {
    if(globalResizeTimer != null) window.clearTimeout(globalResizeTimer);
    globalResizeTimer = window.setTimeout(function() {
        setEqualHeight();
    }, 200);
});

回答by Gabriele Petrioli

You use jquery, so bind it using the .resize()method.

你使用jquery,所以使用.resize()方法绑定它。

$(window).resize(function () {
    setEqualHeight( $('#border') );
});