1.html层面 首先得在页面的 meta 中添加一个新的值:viewport-fit=cover,视图端口被缩放以填充设备显示。
2.css层面 适配 iPhoneX 及以后的刘海屏手机 因为 safe-area-inset-top 避开了状态栏,而底部因为 safe-area-inset-bottom 避开了小黑条,完美的显示在了 Safe Area 的区域中。
body { padding: constant(safe-area-inset-top) constant(safe-area-inset-right) constant(safe-area-inset-bottom) constant(safe-area-inset-left); /* 兼容 iOS < 11.2 / padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left); / 兼容 iOS >= 11.2 */ }
处理 Fixed 和 绝对定位的情况,对该元素单独增加内边距的 padding 来解决。 @element-height: 60px; /* 元素原始高度 */ .element { height: calc(@element-height + constant(safe-area-inset-bottom)); height: calc(@element-height + env(safe-area-inset-bottom)); }
3.可以通过 less、sass 的函数,通过媒体查询来准确的定位到刘海屏的手机,然后写入你希望刘海屏手机展示的任何样式。 .safe-area(@rules) { /* iphone x / xs / 11 pro*/ @media only screen and (device-width: 375px) and (device-height: 812px) and (-webkit-device-pixel-ratio: 3) { @rules(); } /* iphone xr / 11 stackoverflow 提供判断 / @media only screen and (device-width: 414px) and (device-height: 896px) and (-webkit-device-pixel-ratio: 2) { @rules(); } // 实际可用的 xr 判断 @media only screen and (device-width: 375px) and (device-height: 812px) and (-webkit-device-pixel-ratio: 2) { @rules(); } / iphone xs max / 11 pro max */ @media only screen and (device-width: 414px) and (device-height: 896px) and (-webkit-device-pixel-ratio: 3) { @rules(); } }
// 具体使用 .safe-area({ height: 100px; padding-bottom: env(safe-area-bottom-height); });
导航栏 高度所有机型都为44pt; 状态栏 高度大致可以根据是否为刘海屏分为两类。没有刘海屏的大小机型分别为18和20pt,可以近似的看成都是20pt来处理,问题不大,有刘海屏的则统一为44pt高,跟导航栏高度相同。 适配方案: iOS端的适配方案有两种:Apple官方适配方案、机型区分适配、jsBridge方案 使用@supports查询机型是否支持constant() / env()实现兼容代码隔离,个别安卓也会成功进入这个判断,因此加上-webkit-overflow-scrolling: touch的判断可以有效规避安卓机。 @supports ((height: constant(safe-area-inset-top)) or (height: env(safe-area-inset-top))) and (-webkit-overflow-scrolling: touch) { .fullscreen { /* 适配齐刘海 */ padding-top: 20; padding-top: constant(safe-area-inset-top); padding-top: env(safe-area-inset-top);
/* 适配底部小黑条 */ padding-bottom: 0; padding-bottom: costant(safe-area-inset-bottom); padding-bottom: env(safe-area-inset-bottom);} }
开源的Android:JSBridge