H5 移动页面自适应解决方案

本文参考手淘的 H5 页面自适应解决方案。

打开手淘的首页,查看源码,我们会在 head 中发现这样一段代码,这就是手淘页面自适应的关键。

!function(e,t){var n=t.documentElement,d=e.devicePixelRatio||1;function i(){var e=n.clientWidth/3.75;n.style.fontSize=e+"px"}if(function e(){t.body?t.body.style.fontSize="16px":t.addEventListener("DOMContentLoaded",e)}(),i(),e.addEventListener("resize",i),e.addEventListener("pageshow",function(e){e.persisted&&i()}),2<=d){var o=t.createElement("body"),a=t.createElement("div");a.style.border=".5px solid transparent",o.appendChild(a),n.appendChild(o),1===a.offsetHeight&&n.classList.add("hairlines"),n.removeChild(o)}}(window,document)

我们可以讲这段代码复制到我们自己页面的 head 中,其中需要关注两个数字。 1、3.75,这个数字需要根据我们设计图的宽带来调整,把设计图宽度除以100就可以了; 2、16,这个数字是 body 区域的默认字体大小,可以根据自己的需求修改。

最后再添加一段仍是从手淘页面复制过来的 viewport 配置就可以尽情书写代码了:

<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover">

设计图中的 px 像素单位,我们把它除以 100 改为 rem 单位,就可以了,这样不管在什么屏幕上看到的页面比例和设计图都是一模一样的。

<HTML> <iframe src=“https://codesandbox.io/embed/h5-yidongyemianziguaying-kvu0h?fontsize=14&hidenavigation=1&theme=dark&view=preview

   style="width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;"
   title="H5 移动页面自适应"
   allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
   sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
 ></iframe>

</HTML>