You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在iOS Safari中通过JS获取完整视口高度?

在iOS Safari中无需插入元素获取100vh的像素值

针对iOS Safari里window.innerHeight随UI收缩/展开变化的问题,你可以用以下几种无需额外插入DOM元素的方式,获取100vh对应的固定视口完整高度:

方法1:CSS变量+getComputedStyle

先在全局CSS中定义关联100vh的变量(项目未定义的话添加即可):

:root {
  --full-viewport-height: 100vh;
}

然后在JavaScript中直接读取该变量的计算后像素值:

const rootStyle = window.getComputedStyle(document.documentElement);
const fullVhPx = parseFloat(rootStyle.getPropertyValue('--full-viewport-height'));

方法2:CSSOM单位转换API(现代浏览器支持)

iOS Safari 15.4及以上支持CSSUnitValue API,可直接完成单位转换,完全不依赖DOM操作:

// 定义100vh的单位值
const vhUnit = new CSSUnitValue(100, 'vh');
// 转换为px单位
const pxUnit = vhUnit.to('px');
const fullVhPx = pxUnit.value;

方法3:临时修改根元素样式(无需额外CSS)

如果不想新增CSS变量,可临时修改根元素样式获取值后立即恢复,不会影响页面布局:

// 保存根元素原min-height样式
const originalMinHeight = document.documentElement.style.minHeight;
// 临时设置min-height为100vh
document.documentElement.style.minHeight = '100vh';
// 获取计算后的像素值
const fullVhPx = parseFloat(window.getComputedStyle(document.documentElement).minHeight);
// 恢复原样式
document.documentElement.style.minHeight = originalMinHeight;

补充说明

  • 以上方法获取的100vh值和你插入元素测量的结果一致(比如iPhone 12上的745px),不会随Safari的UI状态变化。
  • 兼容旧版iOS Safari(低于15.4)时,优先选择方法1或方法3。

内容的提问来源于stack exchange,提问作者SalutBarbu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 14:20:27