获取屏幕、当前网页和浏览器窗口的大小
技术背景
在前端开发中,经常需要获取屏幕、当前网页和浏览器窗口的大小,以实现响应式设计、布局调整等功能。不同的需求场景可能需要不同的获取方式,同时还要考虑浏览器兼容性。
实现步骤
1. 获取屏幕尺寸
可以使用 screen
对象来获取屏幕的尺寸:
1 2
| window.screen.height; window.screen.width;
|
2. 获取浏览器窗口尺寸
使用 jQuery
1 2 3 4 5 6 7
| $(window).height(); $(window).width();
$(document).height(); $(document).width();
|
使用纯 JavaScript
1 2 3
| const width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; const height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; console.log(width, height);
|
3. 获取可用屏幕尺寸
1 2
| alert(window.screen.availWidth); alert(window.screen.availHeight);
|
4. 获取完整信息的解决方案
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| function sizes() { const contentWidth = [...document.body.children].reduce( (a, el) => Math.max(a, el.getBoundingClientRect().right), 0) - document.body.getBoundingClientRect().x;
return { windowWidth: document.documentElement.clientWidth, windowHeight: document.documentElement.clientHeight, pageWidth: Math.min(document.body.scrollWidth, contentWidth), pageHeight: document.body.scrollHeight, screenWidth: window.screen.width, screenHeight: window.screen.height, pageX: document.body.getBoundingClientRect().x, pageY: document.body.getBoundingClientRect().y, screenX: -window.screenX, screenY: -window.screenY - (window.outerHeight - window.innerHeight), } }
function show() { console.log(sizes()); }
|
核心代码
获取屏幕、网页和窗口尺寸的完整类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| class Size { static get screenWidth() { return Math.round(window.screen.width * window.devicePixelRatio); }
static get screenHeight() { return Math.round(window.screen.height * window.devicePixelRatio); }
static get pageWidth() { return document.body.clientWidth; }
static get pageHeight() { return document.body.clientHeight; }
static get windowWidth() { return window.innerWidth; }
static get windowHeight() { return window.innerHeight; } }
function displaySize() { console.clear(); console.log({ screenWidth: Size.screenWidth, screenHeight: Size.screenHeight, pageWidth: Size.pageWidth, pageHeight: Size.pageHeight, windowWidth: Size.windowWidth, windowHeight: Size.windowHeight }); }
displaySize(); window.addEventListener('resize', displaySize);
|
最佳实践
- 在现代浏览器中,优先使用
window.innerWidth
和 window.innerHeight
来获取浏览器窗口的可用尺寸。 - 对于屏幕尺寸,使用
window.screen.width
和 window.screen.height
。 - 当需要考虑设备像素比时,使用
window.devicePixelRatio
来计算真实的屏幕尺寸。 - 在处理响应式布局时,监听
resize
事件,动态更新尺寸信息。
常见问题
1. jQuery 获取尺寸在某些情况下不准确
在 iOS 中,$(window).height()
可能存在 bug;在移动设备上,$(window).width()
和 $(window).height()
可能无法正确处理缩放效果。可以使用 jQuery.documentSize
插件来解决这些问题。
2. $(document).height()
返回错误数据
在某些响应式布局中,$(document).height()
可能只返回视口高度。可以使用 $( '#wrapper' ).get(0).scrollHeight
来获取元素的实际大小。