怎么解决 ie 中获取 window.screen.width 不正确?

简介: 怎么解决 ie 中获取 window.screen.width 不正确?

问题


最近在调试一个浏览器分辨率的问题时,发现在 ie 下 window.screen.width 不正确。

我电脑的分辨率设置如下:

8fa30d8a92c04b93bdaf0286a7c18923.png


然后在 ie 内核浏览器控制台输出 screen,发现下面 width 为 1920,对此我有点懵逼,按理来说应该是 1366 才对:

36b907d035774b73af5621365ba7558a.png





原因

IE中执行 screen.width 方法,取的只是主显示器的分别率,不论网页实际打开在哪个显示器。

我排查了一下,发现我的主显示器是 1920 x 1080 的。

95a6e9cf5cd144509bed2e35c7cf06db.png



解决


1.获取浏览器信息

// 判断浏览器类型及版本

export function getBrowserInfo () {
  const agent = navigator.userAgent.toLowerCase()
  const regStrFf = /firefox\/[\d.]+/gi
  const regStrChrome = /chrome\/[\d.]+/gi
  const regStrSaf = /safari\/[\d.]+/gi
  const isIE = agent.indexOf('compatible') > -1 && agent.indexOf('msie' > -1) // 判断是否IE<11浏览器
  const isEdge = agent.indexOf('edge') > -1 && !isIE // 判断是否IE的Edge浏览器
  const isIE11 = agent.indexOf('trident') > -1 && agent.indexOf('rv:11.0') > -1
  if (isIE) {
    const reIE = new RegExp('msie (\\d+\\.\\d+);')
    reIE.test(agent)
    const fIEVersion = parseFloat(RegExp['$1'])
    if (fIEVersion === 7) {
      return 'IE/7'
    } else if (fIEVersion === 8) {
      return 'IE/8'
    } else if (fIEVersion === 9) {
      return 'IE/9'
    } else if (fIEVersion === 10) {
      return 'IE/10'
    }
  }
  if (isEdge) {
    return 'Edge'
  }
  // isIE end
  if (isIE11) {
    return 'IE/11'
  }
  // firefox
  if (agent.indexOf('firefox') > 0) {
    return agent.match(regStrFf)
  }
  // Safari
  if (agent.indexOf('safari') > 0 && agent.indexOf('chrome') < 0) {
    return agent.match(regStrSaf)
  }
  // Chrome
  if (agent.indexOf('chrome') > 0) {
    return agent.match(regStrChrome)
  }
}


2.判断是否是IE

import { getBrowserInfo } from './utils.js';
let width = window.screen.width;
const browserInfo = getBrowserInfo();
// 解决ie中获取window.screen.width不正确
if (browserInfo.indexOf('IE') > -1) {
  width = document.body.clientWidth;
}
console.log(width);




目录
相关文章
|
编解码 前端开发 JavaScript
Canvas+HTML+CSS+Position定位
Canvas+HTML+CSS+Position定位
Canvas+HTML+CSS+Position定位
为什么会有window.window这种设计
为啥要搞这个这个看起来貌似很奇葩的设计。 要解答这个问题,还得请出this,我们经常说浏览器中的全局对象是window, 这句话对了,也还没完全对。 全局对象的真实身份应该是全局作用域的this。 window只是为了便于访问this,弄出来的一个属性。
280 0
为什么会有window.window这种设计
|
Web App开发
Chrome浏览器里的-webkit-focus-ring-color
Chrome浏览器里的-webkit-focus-ring-color
115 0
Chrome浏览器里的-webkit-focus-ring-color
|
编解码
window.innerHeight window.outerHeight 与screen.height
本文目录 1. window 2. innerHeight与outerHeight 3. screen.height 4. 实例
360 0
window.innerHeight window.outerHeight 与screen.height
|
JavaScript 前端开发
window.parent ,window.top,window.self 详解及parent和opener的区别
window.parent ,window.top,window.self 详解       在应用有frameset或者iframe的页面时,parent是父窗口,top是最顶级父窗口(有的窗口中套了好几层frameset或者iframe),self是当前窗口, opener是用open方法打开当前窗口的那个窗口。
1923 1
|
Shell
SWT里Slider和Scale的区别
以前以为Slider和Scale之间只是外观的区别,今天发现不是这样的,因为Slider有一个特点:getSelection()能得到的最 大值并不是getMaximum()的值,要减去getThumb()值,后者是中间的滑块所拥有的值,缺省为10,最小为1。
1250 0