likes
comments
collection
share

小程序webview嵌入h5兼容iphonex安全区域

作者站长头像
站长
· 阅读数 14

说明:

  1. 本文小程序专指 微信小程序
  2. iphonex: 实指iphonex及后续刘海屏机器
  3. 安全区域: 本文特指底部安全区域

要做的事情

如何在小程序webview加载h5页面以及使用webview的好处本文不做赘述,文本主要解决为了解决:直接打开h5页面中可以正常适配iphonex安全区域,待h5嵌入到小程序的webview中后不起作用,主要解决h5页面在小程序webview中适配iphonex的问题。

问题表现

h5单独页面浏览时候,可以适配iphonex的底部安全区域(左图),嵌入小程序后适配无效(右图仅h5示例)小程序webview嵌入h5兼容iphonex安全区域小程序webview嵌入h5兼容iphonex安全区域

网上查看了解决方案大概有:

  1. 在小程序里判断当前是否为iphonex,然后将参数拼接到url上,在h5里接受参数,单独增加一个样式,如iphonex-fix
.iphonex-fix {
  padding-bottom: 34px/64rpx;
}
  1. 通过媒体查询,判断当前设备尺寸来确定
@media only screen and (min-device-width: 375px)and (max-device-width: 415px) and (min-device-height: 812px) and (max-device-height: 897px) and (-webkit-min-device-pixel-ratio: 2) {
  .iphonex-fit {
    padding-bottom:34px;
 }
  1. 使用苹果官方推出适配方案css函数env()、constant()来适配 (推荐),具体实现可参考https://www.cnblogs.com/cangq...
@supports (bottom: constant(safe-area-inset-bottom)) or (bottom: env(safe-area-inset-bottom)) {
  @action-button-height: 60px;
  .my__container {
      padding-bottom: calc(~"@{action-button-height} + constant(safe-area-inset-bottom)");
      padding-bottom: calc(~"@{action-button-height} + env(safe-area-inset-bottom)");
    }

  .my__action {
      padding-bottom: calc(~"@{action-button-height} + constant(safe-area-inset-bottom)");
      padding-bottom: calc(~"@{action-button-height} + env(safe-area-inset-bottom)");
    }

}

本文也是在毫不犹豫的选择来 3种解决方案,嵌入小程序后发现的,问题点在于在h5单独显示正常,放到微信开发者工具中不正常,webview又无法像chrome浏览器进行debugger。迫于交付压力,改用了第2种方案,但是又甘心啊。。问题的转折点在于偶然发现最新版的开发者工具,在webview页面中多了一个debugger按钮,点开发现竟然可以调试嵌入的h5页面了

小程序webview嵌入h5兼容iphonex安全区域

解决方式

经过排查发现,通过第三种方法写的css,在小程序下是可以生效的,但是由于样式优先级问题被覆盖掉了。解决方案就是在支持安全区域的机型上,增加css权重,在外层嵌套了my-wrap

@supports (bottom: constant(safe-area-inset-bottom)) or (bottom: env(safe-area-inset-bottom)) {
  
  // 增加class权重
  .my-wrap  {
    
    @action-button-height: 60px;
    .my__container {
      padding-bottom: calc(~"@{action-button-height} + constant(safe-area-inset-bottom)");
      padding-bottom: calc(~"@{action-button-height} + env(safe-area-inset-bottom)");
    }

    .my__action {
      padding-bottom: calc(~"@{action-button-height} + constant(safe-area-inset-bottom)");
      padding-bottom: calc(~"@{action-button-height} + env(safe-area-inset-bottom)");
    }
  
  }

}