前言
本文章针对H5开发的单页全屏无滚动页面。
解决方案
整体采用vw、vh作为基本单位,采用flex布局,针对字体使用rem单位。
多终端适配
针对app包下载等业务场景,需要识别对应的终端,采用不同的地址下载。针对微信特定情况,需要引导用户去往浏览器打开。
识别终端类型可以采用如下方式:
// 微信
const isWeixin = () => {let ua = window.navigator.userAgent.toLowerCase();return ua.match(/MicroMessenger/i) == 'micromessenger';
};// Android
const isAndroid = () => {let u = window.navigator.userAgent;return u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
};// iOS
const isIOS = () => {let u = window.navigator.userAgent;return !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
};
横竖屏切换
js作为浏览器运行语言,无法控制设备的横竖屏切换。我们可以做一些兼容的处理。
首先,要监测出用户切换了横竖屏,检测方法:
- window.matchMedia
const checkMediaOritation = () => {const mql = window.matchMedia('(orientation: portrait)');mql.addListener(() => {if (mql.matches) {// 竖屏} else {// 横屏}});
};
- window.innerWidth > window.innnerHeight
window.addEventListener("resize", () => {let h = window.innerHeight, w = window.innerWidth;if(h > w) {// 竖屏} else {// 横屏}
});
监测到用户切换横竖屏后,常见处理方式有三种:
- 给予用户提示信息,让用户保持其中一种模式操作
- 页面整体旋转,保持页面布局不变
- 页面自适应,出现滚动条
其中第1种和第3种比较好理解,第2种处理方式如下:
- 采用js控制transform方式整体rotate(-90deg)
// 以竖屏布局为主,适配横屏let h = window.innerHeight, w = window.innerWidth;if(h > w) {document.getElementById("rootElement").transform = "rotate(0deg)";} else {let height = document.getElementById("rootElement").clientHeight;let width = document.getElementById("rootElement").clientWidth;document.getElementById("rootElement").transform = "rotate(-90deg)";document.getElementById("rootElement").transformOrigin = height / 2 + "px " + height / 2 + "px"; // 如果rotate 90deg,则这里取 width / 2}
- 在第一种方式上优化,用css的方式控制
let h = window.innerHeight, w = window.innerWidth;if(h > w) {rootElement.className = "someClass";} else {rootElement.className += " rotate";}
然后把所有的切换后的样式写在rotate上,rotate下所有元素的单位vh 和 vw互换。对应的rem也要同步调整
.rotate {width: 100vh;height: 100vw;transform: rotate(-90deg);transform-origin: 50vh 50vh;
}
如有问题,还望不吝赐教。