web前端开发前端攻城狮Javascript收集

移动端适配小结

2017-11-05  本文已影响213人  前端进阶之旅

原文地址 http://blog.poetries.top/2017/11/05/mobile-layout

一、为什么要做适配

二、适配方案

三、单位

四、百分比适配(常用)

固定高度,宽度百分比适配

640设计稿为例,在外层容器上设置最大以及最小的宽

#wrapper {
    max-width: 640px; /*设置设计稿的宽度*/
    min-width: 300px;
    margin: 0 auto;
}

后面的区块布局都用百分比,具体元素大小用px计算

五、Rem适配(常用)

head加入常见的meta属性

<meta name="format-detection" content="telephone=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<!--这个是关键-->
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0,minimum-scale=1.0">

把这段代码加入head中的script预先加载

// rem适配用这段代码动态计算html的font-size大小
(function(win) {
    var docEl = win.document.documentElement;
    var timer = '';

    function changeRem() {
        var width = docEl.getBoundingClientRect().width;
        if (width > 750) { // 750是设计稿大小
            width = 750;
        }
        var fontS = width / 10; // 把设备宽度十等分 1rem=10px
        docEl.style.fontSize = fontS + "px";
    }
    win.addEventListener("resize", function() {
        clearTimeout(timer);
        timer = setTimeout(changeRem, 30);
    }, false);
    win.addEventListener("pageshow", function(e) {
        if (e.persisted) { //清除缓存
            clearTimeout(timer);
            timer = setTimeout(changeRem, 30);
        }
    }, false);
    changeRem();
})(window)

布局细节

body {
    width: 10rem;
    margin: auto;
}

后面的区块都以百分比布局

<div class="wrapper">
   <header><header>
   <section><section>
   <section><section>
   <section><section>
   <section><section>
</div>
section,
header {
    width: 100%;
}

把视觉稿中的 px 转换成 rem

首先,目前日常工作当中,视觉设计师给到前端开发人员手中的视觉稿尺寸一般是基于 640px750px 以及 1125px 宽度为准。甚至为什么?大家应该懂的(考虑Retina屏)

假定设计稿的大小为750,那么我们则将整个图分成10等份来看。<html> 对应的 font-size75px

html{
    font-size: 75px;
}

那么,我们现在就可以比对设计稿,比如设计稿中,有一个div元素,宽度,高度都为20px,那么我们这样写即可(可以用 markman标准设计稿的元素大小)

div {
    height: 0.27rem; /*20/75*/
    width: 0.27rem;
}

比如当我们切换到320设备大小的时候,这时候1rem=32px; div的像素实际是0.27*32=8.64px 0.27是我们在已知设计稿是750的情况下计算出来的,rem用来动态计算而已

如何快速计算

在实际生产当中,如果每一次计算 px 转换 rem ,或许会觉得非常麻烦

插件使用方法

文字适配的解决方案

六、缩放比适配

固定宽度,改变缩放比例适配

// 缩放比例适配方案--用这个代码 
var width = window.screen.width,
    fixedW = 320, //设计稿宽度的一半
    scale = width / fixedW, // 缩放比例
    meta = document.createElement('meta'),
    metaAttr = {
        name : 'viewport',
        content : 'width='+fixedW+', initial-scale='+scale+', maximum-scale='+scale+', user-scalable=0'
    };
    for (var key in metaAttr) {
        meta[key] = metaAttr[key];
    }
    document.head.appendChild(meta);

七、像素比适配

八、小结

关于移动端布局方案有很多,rem和百分比运用最多的

相关文章阅读

上一篇 下一篇

猜你喜欢

热点阅读