Javascript 调整大小事件错误

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

Javascript resize event faulty

javascripthtmlresizedom-events

提问by MinestoPix

I don't know why this doesn't work:

我不知道为什么这不起作用:

window.addEventListener('load', setSize(), false);
window.addEventListener('resize', setSize(), false);

function setSize(){
    width = window.innerWidth;
    console.log(width);
}

It logs the width right after load, but it doesn't do that when I resize.

它在加载后立即记录宽度,但是当我调整大小时它不会这样做。

回答by sanchez

Instead of executing the function (and passing the result) :

而不是执行函数(并传递结果):

window.addEventListener('load', setSize(), false);
window.addEventListener('resize', setSize(), false);

you should pass a reference to the function:

您应该传递对函数的引用:

window.addEventListener('load', setSize, false);
window.addEventListener('resize', setSize, false);

The function will execute when the event listener triggers.

该函数将在事件侦听器触发时执行。