您的位置:首页 > Web前端 > JavaScript

通过媒体查询meta和JS转换REM单位实现100%自适应

2016-05-27 15:18 561 查看
移动端页面设置根节点(html)font-size大小转换REM单位实现100%自适应,通过媒体查询meta和JS两种方法实现

第一种方法

媒体查询 meta - REM单位字体设置

/* 媒体查询 - 字体设置 */
/* 平滑过渡 */
html{ -webkit-transition: font-size .2s ease-out; transition: font-size .2s ease-out; }
/* 设计稿宽度=640时, 4rem=400px, 1rem=100px, .5rem = 50px, .1rem = 10px 以此类推 */
@media screen and (max-width: 1280px) {
html{ font-size: 200px; }
}
@media screen and (max-width: 1200px) {
html{ font-size: 187.5px; }
}
@media screen and (max-width: 1120px) {
html{ font-size: 175px; }
}
@media screen and (max-width: 1080px) {
html{ font-size: 168.75px; }
}
@media screen and (max-width: 960px) {
html{ font-size: 150px; }
}
@media screen and (max-width: 880px) {
html{ font-size: 137.5px; }
}
@media screen and (max-width: 840px) {
html{ font-size: 131.25px; }
}
@media screen and (max-width: 800px) {
html{ font-size: 125px; }
}
@media screen and (max-width: 720px) {
html{ font-size: 112.5px; }
}
@media screen and (max-width: 640px) {
html{ font-size: 100px; }
}
@media screen and (max-width: 600px) {
html{ font-size: 93.75px; }
}
@media screen and (max-width: 560px) {
html{ font-size: 87.5px; }
}
@media screen and (max-width: 480px) {
html{ font-size: 75px; }
}
@media screen and (max-width: 400px) {
html{ font-size: 62.5px; -webkit-transition: none; }
}
@media screen and (max-width: 360px) {
html{ font-size: 56.25px; }
}
@media screen and (max-width: 320px) {
html{ font-size: 50px; }
}


/* 设计稿宽度=640时, 4rem=400px, 1rem=100px, .5rem = 50px, .1rem = 10px 以此类推 */

@media screen and (max-width: 640px) {
html{ font-size: 100px; }
}
100px*0.01 = 1rem

示例:
img{width:40px, height:35px}
转换rem 40px*0.01 = 0.04rem, 35px*0.01 = 0.035rem
img{width:0.01rem, height:0.035rem}

@media screen and (max-width: 640px) {
html{ font-size: 40px; }
}
40px*0.025 = 1rem

示例:
img{width:40px, height:35px}
转换rem 40px*0.025 = 1rem, 35px*0.025 = 0.875rem
img{width:1rem, height:0.875rem}

@media screen and (max-width: 640px) {
html{ font-size: 20px; }
}
20px*0.05 = 1rem

示例:
img{width:40px, height:35px}
转换rem 40px*0.05 = 2rem, 35px*0.05 = 1.75rem
img{width:2rem, height:1.75rem}

第二种方法

JS根据设备宽度设置根节点(html)font-size字体大小
(function () { document.addEventListener('DOMContentLoaded', function () { var deviceWidth = document.documentElement.clientWidth; document.documentElement.style.fontSize = deviceWidth / 6.4 + 'px'; }, false); window.onresize = function(){ var deviceWidth = document.documentElement.clientWidth; document.documentElement.style.fontSize = deviceWidth / 6.4 + 'px'; }; })();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息