javascript - 调整浏览器窗口大小时,addEventListener 'resize' 不会触发

标签 javascript addeventlistener window-resize device-orientation

我需要检测移动设备视口(viewport)宽度的变化。我使用以下代码来检测浏览器窗口的调整大小更改,但调整窗口大小时 addEventListener 不会触发我的函数:

<html>
<head>
</head>
<body>

<div id="size">-</div><br>
<div id="orientation">-</div>

<script>

window.addEventListener('resize', sizeChanged() );

function sizeChanged() {

    var w=window.outerWidth;
    var h=window.outerHeight;
    var txt='<b>sizeChanged:</b><br> W=' + w + 'px<br> H=' + h+'px';
    document.getElementById('size').innerHTML=txt;
    console.log(txt);
}

window.addEventListener('orientationchange', orientationChanged() );

function orientationChanged() {

  var w=window.outerWidth;
  var h=window.outerHeight;
  var txt='<b>orientationChanged:</b><br> W=' + w + 'px<br> H=' + h+'px';
  document.getElementById('orientation').innerHTML=txt;
  console.log(txt);

}

</script>

</body>
</html>

我在 FF 62.0.3、Chrome 70.0.3538.77 和 IE11 上尝试了上面的代码。

有人知道我的代码有什么问题吗?

最佳答案

您突然调用这些函数,因此基本上,您正在传递这些函数的结果,在本例中为undefined

您需要将函数作为引用(参数)传递,例如,

window.addEventListener('resize', sizeChanged); // Look at the missing parentheses.
window.addEventListener('orientationchange', orientationChanged); // Look at the missing parentheses.

关于javascript - 调整浏览器窗口大小时,addEventListener 'resize' 不会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53018261/

相关文章:

javascript - 使用 for 循环向多个元素添加事件监听器并传递不同的参数

javascript - 调整窗口大小时调用函数

javascript - Angular 6 创建 TemplateRef 的实例

javascript - 为什么我的事件监听器不在函数内工作?

javascript - 如何拆分和添加字符串中的各个值?

javascript - 在使用html,css和javascript的简单菜单中冒泡

java - FXML 最小高度和最大宽度属性被忽略了吗?

java - Swing - windowStateChanged 事件问题

javascript - 在 LocalStorage 中构建数组

javascript - 如何在 jquery 中获取鼠标落下时范围 slider 的精确值