怎么解决 ie 中获取 window.screen.width 不正确?
Posted 凯小默
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了怎么解决 ie 中获取 window.screen.width 不正确?相关的知识,希望对你有一定的参考价值。
问题
最近在调试一个浏览器分辨率的问题时,发现在 ie 下 window.screen.width
不正确。
我电脑的分辨率设置如下:
然后在 ie 内核浏览器控制台输出 screen,发现下面 width 为 1920,对此我有点懵逼,按理来说应该是 1366 才对:
原因
IE中执行 screen.width
方法,取的只是主显示器的分别率,不论网页实际打开在哪个显示器。
我排查了一下,发现我的主显示器是 1920 x 1080
的。
解决
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);
以上是关于怎么解决 ie 中获取 window.screen.width 不正确?的主要内容,如果未能解决你的问题,请参考以下文章