在JavaScript中,获取手机屏幕的宽度和高度可以通过多种方式实现,主要依赖于window
对象提供的属性和方法。以下是一些常用的方法:
window.innerWidth
和window.innerHeight
这些属性返回浏览器窗口的内部宽度和高度(包括滚动条)。
let width = window.innerWidth;
let height = window.innerHeight;
console.log(`屏幕宽度: ${width}px, 屏幕高度: ${height}px`);
screen.width
和screen.height
这些属性返回设备屏幕的物理宽度和高度。
let screenWidth = screen.width;
let screenHeight = screen.height;
console.log(`屏幕宽度: ${screenWidth}px, 屏幕高度: ${screenHeight}px`);
为了更精确地处理高分辨率屏幕(如Retina显示屏),可以使用window.devicePixelRatio
来获取设备像素比,并据此调整逻辑像素的计算。
let dpr = window.devicePixelRatio || 1;
let logicalWidth = screen.width / dpr;
let logicalHeight = screen.height / dpr;
console.log(`逻辑屏幕宽度: ${logicalWidth}px, 逻辑屏幕高度: ${logicalHeight}px`);
window.addEventListener('load', function() {
let width = window.innerWidth;
let height = window.innerHeight;
console.log(`屏幕宽度: ${width}px, 屏幕高度: ${height}px`);
});
/* 示例媒体查询 */
@media (max-width: 600px) {
body {
font-size: 14px;
}
}
通过上述方法,可以有效地获取并处理手机屏幕的宽度和高度,从而优化网页和应用在不同设备上的显示效果。
领取专属 10元无门槛券
手把手带您无忧上云