背景:最近要对之前的H5页面在iPhone X上做适配。下面就说下我在实际项目中是怎么适配的。
写了一个测试页面,在没有适配的情况下页面会被顶部的刘海和底部的Home Indicator遮挡。 页面代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<title>iPhone X 适配测试页面</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body{
padding: 0;
margin: 0;
}
.top{
width: 100%;
height: 1rem;
line-height: 1rem;
font-size: 0.3rem;
border-bottom: 1px solid #ccc;
}
.bottom{
position: fixed;
bottom:0;
left: 0;
width: 100%;
height: 1.5rem;
line-height: 1.5rem;
font-size: 0.4rem;
background-color: #cccccc;
}
</style>
</head>
<body>
<div class="top">这是顶部这是顶部这是顶部这是顶部</div>
<div class="bottom">这是底部这是底部这是底部</div>
<script type="text/javascript" src="../js/libs/zepto.min.js"></script>
<script>
$(function(){$(window).resize(function(){reViewport()});$(window).resize();setTimeout(function(){$(window).resize()},50)});function loadCss(path){var head=document.getElementsByTagName("head").item(0);var css=document.createElement("link");css.rel="stylesheet";css.type="text/css";css.id="loadCss";css.href=path;head.appendChild(css)}var reViewport=function(width,maxScale){width=width||750;maxScale=maxScale||1;var $window=$(window),winW=$window.width(),minW=width;ratio=winW/minW;if(ratio>maxScale){ratio=maxScale}$("html").css({fontSize:String(ratio*100)+"px"});$("body").css({opacity:1});return ratio};
</script>
</body>
</html>
页面截图如下:

很明显,页面顶部和底部被遮挡了,这样当然是不能容忍的。于是
第一种方案
首先搜索了下大家对前端页面是怎么适配的。
网上大部分的文章都是这样说的。
1.第一步在meta标签中添加viewport-fit=cover
<meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover">
2.第二步添加属性
body{padding-top: constant(safe-area-inset-top);
padding-left: constant(safe-area-inset-left);
padding-right: constant(safe-area-inset-right);
padding-bottom: constant(safe-area-inset-bottom);
}
再打开下页面,确实页面的顶部和底部没有被遮挡。截图如下:

但是把这段代码拿到实际项目中发现没有生效,最后经过排查原因是因为我们的H5页面是通过webview内嵌的,webview设置了页面全屏
webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;//设置全屏
这个导致了上面适配代码的失效。
第二种方案
所以还要换解决方案,其实就是对iPhone X单独做适配,就是增加顶部和底部的高度。具体代码如下:
@media only screen and (device-width: 375px) and (device-height: 812px) and
(-webkit-device-pixel-ratio: 3) {
.top{
padding-top: 44px;
}
.bottom{
padding-bottom: 34px;
}
}
最后截图如下:

小技巧分享,有时候可能直接设置
height来增加高度,如果你的页面是采用rem布局的,你可以直接使用.top{height: calc(xrem + 44px)},.bottom{height: calc(xrem + 44px)},其中x表示原来的高度值。
以上就是在项目中的实践了。