如何在窗口调整大小时调用 jQuery 中的函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10312696/
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 09:07:41  来源:igfitidea点击:

How to call a function in jQuery on window resize?

jqueryfunction

提问by Luca Frank Guarini

I've this code:

我有这个代码:

<script>
            $(document).ready(function larg(){
            var larghezza = $(document).width();
            $("p.width").text("The width for the " + larghezza + 
                " is px.");
            });

            $(window).resize(function() {
            larg(); 
            });
            </script>

I would like to call the function "larg" on window resize, but it doesn't work.. How to do that??

我想在窗口调整大小时调用函数“大”,但它不起作用..怎么做??

Thanks

谢谢

回答by LHolleman

You can't declare functions that way, use it like this.

你不能那样声明函数,像这样使用它。

<script>
 $(document).ready(larg);

 $(window).resize(larg);

 function larg(){
  var larghezza = $(document).width();
  $("p.width").text("The width for the " + larghezza + " is px.");
 }
</script>

EDIT: changed code a bit, thanks commenters

编辑:稍微改变了代码,感谢评论者

回答by Shyam Bhagat

Please call the following method:

请调用以下方法:

window.dispatchEvent(new Event('resize'));