最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - addEventListener 'resize' doesnt fire when resizing the browser window - Stack Overflow

programmeradmin9浏览0评论

i need to detect changes of the viewport width for mobiles. Im using the following code to detect resize changes of the browser window but the addEventListener doesnt fire my functions when the window is resized:

<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>

I trid the code above with FF 62.0.3, Chrome 70.0.3538.77 and IE11.

Does anyone have an idea what's wrong with my code?

i need to detect changes of the viewport width for mobiles. Im using the following code to detect resize changes of the browser window but the addEventListener doesnt fire my functions when the window is resized:

<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>

I trid the code above with FF 62.0.3, Chrome 70.0.3538.77 and IE11.

Does anyone have an idea what's wrong with my code?

Share Improve this question asked Oct 27, 2018 at 2:36 Peter FurzPeter Furz 651 silver badge8 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

You're suddenly calling those functions, so basically, you're passing the result from those functions, in this case, undefined.

You need to pass the function as a reference (param), for example,

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

评论列表(0)

  1. 暂无评论