rem自适应手机端布局

通过js根据屏幕设备尺寸的大小,改变根元素的值:

<script>

var html = document.querySelector("html");
var    rem = html.offsetWidth / 7.5;
 html.style.fontSize = rem + "px";

</script>

 

最简单的适配方案:

7.5 为 设计图的宽度除以100;

H5端自适应框架 使用方便,设计图的1px对应0.01rem,设计图的字体大小24px对应0.24rem,就是如此简单!

在header中写入以下代码,实时更新html的fontsize:

css样式:
正常情况下的写法:
div{
width:100px;
height:200px;
border:1px solid #F00;
padding:20px;
}
使用自适应方法,px用rem ,1px的仍然可以用1px,可以改写为:
div{
width:1rem;
height:2rem;
border:1px solid #F00;
padding:0.2rem
}

 

 

方法二:手机端自适应:

js代码:

(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 = 50 * (clientWidth / 375) + 'px';
        };
        if (!doc.addEventListener) return;
        win.addEventListener(resizeEvt, recalc, false);
        doc.addEventListener('DOMContentLoaded', recalc, false);
    }(document,window));

  

3. iphone4/iphone5/iphone6/iphone6p 的css media query:媒体查询

@media (device-height:480px) and (-webkit-min-device-pixel-ratio:2){/* 兼容iphone4/4s */

    .class{}

}


@media (device-height:568px) and (-webkit-min-device-pixel-ratio:2){/* 兼容iphone5 */

    .class{}

}

@media(min-device-width:375px)and(max-device-width:667px)and(-webkit-min-device-pixel-ratio:2){

  

方法三:js代码

 var deviceWidth = document.documentElement.clientWidth;
  if (deviceWidth > 750) deviceWidth = 750;
  document.documentElement.style.fontSize = deviceWidth / 7.5 + 'px';

  css代码:

@media screen and (max-width:321px){
	  html{font-size:15px}
 }

@media screen and (min-width:321px) and (max-width:400px){
	  html{font-size:16px}
}

@media screen and (min-width:400px){
	  html{font-size:18px}
}

  

注意:1、手机端适配 rem、或者 百分号

2、手机端引入背景图时,会出现图片样式变,通过background-size: 0.9rem 0.9rem;

3、手机端需要引入:<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0,minimal-ui">

 

 

手机端的适配方法有多种,会不断更新~

 

posted on 2018-11-06 23:00  婧星  阅读(354)  评论(0编辑  收藏  举报

导航