js如何获取设备分辨率兼容所有浏览器
时间: 2023-09-24 11:12:01 浏览: 59
要获取设备的分辨率并兼容所有浏览器,可以使用`window.screen`对象提供的属性。以下是一个获取设备分辨率的示例代码:
```javascript
function getDeviceResolution() {
var width = window.screen.width || window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var height = window.screen.height || window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
return {
width: width,
height: height
};
}
var resolution = getDeviceResolution();
console.log(resolution.width + " x " + resolution.height);
```
在上述代码中,我们定义了一个`getDeviceResolution`函数,它尝试使用不同的方式来获取设备的分辨率:
- 首先,它尝试访问`window.screen.width`和`window.screen.height`属性,这是一种常见的获取分辨率的方法。
- 如果上述属性不可用,则尝试使用`window.innerWidth`和`window.innerHeight`获取视口的宽度和高度。
- 如果之前的属性也不可用,则使用`document.documentElement.clientWidth`和`document.documentElement.clientHeight`获取文档元素的宽度和高度。
- 最后,如果以上方法都不可用,则使用`document.body.clientWidth`和`document.body.clientHeight`获取文档体的宽度和高度。
返回的结果是一个包含宽度和高度的对象。在示例代码中,我们将获取到的分辨率打印到控制台上。
请注意,由于浏览器的差异性,不同浏览器可能在获取分辨率时使用不同的属性。因此,通过尝试多种属性来获取分辨率可以增加兼容性。