admin管理员组

文章数量:1330677

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.

本文标签: javascriptaddEventListener 39resize39 doesnt fire when resizing the browser windowStack Overflow