【问题标题】:addEventListener 'resize' doesnt fire when resizing the browser window调整浏览器窗口大小时,addEventListener 'resize' 不会触发
【发布时间】:2018-10-27 02:36:33
【问题描述】:

我需要检测手机视口宽度的变化。我使用以下代码来检测浏览器窗口的调整大小变化,但是当窗口调整大小时 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 尝试了上面的代码。

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

【问题讨论】:

    标签: javascript addeventlistener window-resize device-orientation


    【解决方案1】:

    你突然调用了这些函数,所以基本上,你是在传递这些函数的结果,在这种情况下,undefined

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

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

    【讨论】:

      猜你喜欢
      • 2023-04-07
      • 2015-04-20
      • 2012-02-23
      • 1970-01-01
      • 1970-01-01
      • 2012-05-20
      • 2016-10-31
      • 2012-05-23
      • 1970-01-01
      相关资源
      最近更新 更多