在变量中存储浏览器窗口大小并在更改时进行更新

时间:2019-05-31 22:35:50

标签: javascript variables

我正在使用const deviceWidth = window.innerWidth;将窗口宽度存储到变量中。但是,这很棒,我希望用户每次调整窗口大小时都可以更新该变量。如何实现的?

2 个答案:

答案 0 :(得分:0)

我将利用窗口调整大小事件来使您的变量保持更新:

https://developer.mozilla.org/en-US/docs/Web/API/Window/resize_event

基本上,您可以创建一个可以在任何窗口调整大小后运行的函数,然后设置变量。

const heightOutput = document.querySelector('#height');
const widthOutput = document.querySelector('#width');

function reportWindowSize() {
  heightOutput.textContent = window.innerHeight;
  widthOutput.textContent = window.innerWidth;
}

window.onresize = reportWindowSize;
<p>Resize the browser window to fire the <code>resize</code> event.</p>
<p>Window height: <span id="height"></span></p>
<p>Window width: <span id="width"></span></p>

答案 1 :(得分:-1)

当窗口更改大小时,它将触发“调整大小”事件。 Details here

您需要侦听此事件并相应地更新变量。 Details here