📜  获取屏幕大小的javascript(1)

📅  最后修改于: 2023-12-03 15:41:27.989000             🧑  作者: Mango

获取屏幕大小的JavaScript

在前端开发中,获取屏幕大小是一个常见操作。下面介绍一些用于获取屏幕大小的JavaScript方法。

1. window.innerWidth和window.innerHeight属性

window.innerWidth和window.innerHeight属性是最常用的获取屏幕大小的方法,它们可以获取浏览器窗口的视口(viewport)大小,不包括滚动条和边框。

const width = window.innerWidth;
const height = window.innerHeight;

console.log(`Window size: ${width} x ${height}`);
2. document.documentElement.clientWidth和document.documentElement.clientHeight属性

document.documentElement.clientWidth和document.documentElement.clientHeight属性也可以用来获取浏览器窗口的视口大小,它们与window.innerWidth和window.innerHeight在大多数情况下是等效的。

const width = document.documentElement.clientWidth;
const height = document.documentElement.clientHeight;

console.log(`Window size: ${width} x ${height}`);
3. screen.width和screen.height属性

screen.width和screen.height属性可以获取屏幕的大小(以像素为单位),包括可见的和不可见的部分。

const width = screen.width;
const height = screen.height;

console.log(`Screen size: ${width} x ${height}`);
4. window.screen.availWidth和window.screen.availHeight属性

window.screen.availWidth和window.screen.availHeight属性可以获取屏幕的可用大小(以像素为单位),即屏幕除去任务栏和其他工具栏后的大小。

const width = window.screen.availWidth;
const height = window.screen.availHeight;

console.log(`Available screen size: ${width} x ${height}`);

以上就是获取屏幕大小的几种常见JavaScript方法,开发者可以根据自己的实际需求选择最适合的方法。