原生H5屏幕适配
找了很多关于品目适配的资料,我们在使用js/jQuery编写H5时需要做屏幕适配,通常有几种方法:
不管使用啥方法,都在head里面添加<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
- 采用媒体查询方案:
/* //iphone4 & phone4s 2@x*/
@media only screen and (device-width: 320px) and (device-height: 480px) and (-webkit-device-pixel-ratio: 2) {
}
/* //iphoneX & phoneXs 3@x*/
@media only screen and (device-width: 375px) and (device-height: 812px) and (-webkit-device-pixel-ratio: 3) {
}
/* //iphone Xs Max 3@x*/
@media only screen and (device-width: 414px) and (device-height: 896px) and (-webkit-device-pixel-ratio:3) {
}
/* //iphone XR 2@x*/
@media only screen and (device-width: 414px) and (device-height: 896px) and (-webkit-device-pixel-ratio:2) {
}
/* LG optimus*/
@media only screen and (device-width: 384px) and (device-height: 640px) {
}
/* Nexus 10*/
@media only screen and (device-width: 800px) and (device-height: 1280px) {
}
/* pixel 2 XL*/
@media only screen and (device-width: 411px) and (device-height: 823px) {
}
/* ipad*/
@media only screen and (device-width: 768px) and (device-height: 1024px) {
}
/* ipad pro*/
@media only screen and (device-width: 1024px) and (device-height: 1366px) {
}
我通常不咋使用媒体查询,特麻烦。
- 使用js计算屏幕宽度进行适配,使用rem。如果使用Hbuilder X编辑器,可以将px计算为rem。16px=1rem,用起来还是比较方便。
首先建一个js文件:根据设计稿的大小和px与rem的转换值定义初始值。我这个是使用375的设计稿,由于编辑器Hbuilder X可以自动计算,1rem = 16px,所以这里就运用了16/375就可以达到设计稿的适配效果,当然可以根据需要进行修改。
(function(doc, win) {
var docEl = doc.documentElement;
resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize';
recalc = function() {
var clientWidth = docEl.clientWidth;
if (!clientWidth) return;
docEl.style.fontSize = 16 * (clientWidth / 375) + 'px';
};
if (!doc.addEventListener) return;
win.addEventListener(resizeEvt, recalc, false);
doc.addEventListener('DOMContentLoaded', recalc, false);
}(document, window));
个人感觉rem对原生js/jQuery编写移动端的H5还是比较好用,欢迎推荐更好用的方案。