温馨提示:本文翻译自stackoverflow.com,查看原文请点击:javascript - How to get height and width after window resize
javascript asp.net-mvc-3

javascript - 调整窗口大小后如何获取高度和宽度

发布于 2020-03-27 15:59:50

我有一个scorm模块,它在我的js文件的window.open中的resizable = 1的新窗口中启动:

function OpenScormModuleWindow(scormModuleId, scormModuleUrl, title, width, height) 
{
  _scormModuleId = scormModuleId;
  InitializeUserScormModule();
  scormModuleWindow = window.open(scormModuleUrl, "title", "width=" + width + ", height=" + height + ", resizable = 1");
  scormModuleWindow.focus();
}

我认为我有:

  var myWidth = 0, myHeight = 0;
  if (typeof (window.innerWidth) == 'number')
  {
      myWidth = window.innerWidth;
      myHeight = window.innerHeight;
  }
  else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight))
  {
      myWidth = document.documentElement.clientWidth; myHeight = document.documentElement.clientHeight;
  }
  else if (document.body && (document.body.clientWidth || document.body.clientHeight))
  {
      myWidth = document.body.clientWidth; myHeight = document.body.clientHeight;
  }

我得到高度和宽度,但不正确

用户现在可以调整大小,当窗口尺寸正确时,如何获取高度和宽度?

我需要获取这些值,以便保存它,下次打开窗口时,它是正确的大小。

谢谢

查看更多

查看更多

提问者
charlie_cat
被浏览
14
2017-05-23 20:16

使用一个事件侦听器,它侦听调整大小,然后可以重置值:

window.addEventListener('resize', setWindowSize);

function setWindowSize() {
  if (typeof (window.innerWidth) == 'number') {
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else {
    if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
      myWidth = document.documentElement.clientWidth;
      myHeight = document.documentElement.clientHeight;
    } else {
      if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
      }
    }
  }
}

如果您需要跨浏览器解决方案,请使用jQuery$.on('resize', func))或查看JavaScript窗口调整大小事件