可以使用JavaScript中的window.innerWidth
和window.innerHeight
属性来获取浏览器窗口的大小。
const windowWidth = window.innerWidth;
const windowHeight = window.innerHeight;
console.log(`浏览器窗口大小为 ${windowWidth}px x ${windowHeight}px`);
其中,window.innerWidth
和window.innerHeight
分别表示浏览器窗口的宽度和高度,单位为像素(px)。
需要注意的是,这种方法获取的浏览器窗口大小不包括浏览器工具栏、地址栏和滚动条等占用空间。如果需要获取包括这些占用空间的浏览器可视区域大小,可以使用document.documentElement.clientWidth
和document.documentElement.clientHeight
属性。
const viewportWidth = document.documentElement.clientWidth;
const viewportHeight = document.documentElement.clientHeight;
console.log(`浏览器可视区域大小为 ${viewportWidth}px x ${viewportHeight}px`);
其中,document.documentElement.clientWidth
和document.documentElement.clientHeight
分别表示浏览器可视区域的宽度和高度,单位也是像素(px)。