手机端适配方案 媒体查询和flexbale

方法一  flexible
一、npm 包安装
lib-flexible 淘宝适配方案 
px2rem px自动转rem

npm install lib-flexible --save
npm install px2rem-loader 

二、在main.js中引入lib-flexible**
import 'lib-flexible/flexible.js'

三、配置build/utils.js
var px2remLoader = {
loader: 'px2rem-loader',
options: {
remUnit: 75
}
}


// generate loader string to be used with extract text plugin
function generateLoaders (loader, loaderOptions) {
var loaders = [cssLoader,px2remLoader]
if (loader) {
loaders.push({
loader: loader + '-loader',
options: Object.assign({}, loaderOptions, {
sourceMap: options.sourceMap
})
})
}
方法二媒体查询

/* 定一个基准值:100 给设计图中 1rem应该等于多少px 100 */
/* 根据基准值适配不同的屏幕 设计图的大小100/750 = 当前屏幕的fontsize/当前屏幕的大小 */
@media (min-width: 320px) {
html {
font-size: 42.67px
}
}

@media (min-width: 375px) {
html {
font-size: 50px
}
}

@media (min-width: 750px) {
html {
font-size: 100px
}
}
@media (min-width: 414px) {
html {
font-size: 55.2px
}
}

@media (min-width: 420px) {
html {
font-size: 56px
}
}

@media (min-width: 480px) {
html {
font-size: 64px
}
}
 
js 适配
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.rem {
width: 2rem;
height: 2rem;
font-size: 0.5rem;
background-color: red;
}

p {
width: 3rem /* 300/100 */
}
</style>
<script>
// 防抖
//根据屏幕的大小修改html的fontsize
function fn() {
var screenWidth = window.innerWidth;
var baseWidth = 100
var designWidth = 750
// 求html的fontSize
if (screenWidth <= 320) {
screenWidth = 320
}

if (screenWidth >= 750) {
screenWidth = 750
}
document.documentElement.style.fontSize = baseWidth/designWidth*screenWidth + 'px'
}
fn()
window.addEventListener('resize', fn)
 
</script>
</head>
<body>
<!-- 这段script应该在上面,不然会闪烁 -->
 


<div class="rem">我是一个中国人</div>

 
</body>
</html>

  

posted on 2018-11-07 18:50  田庚的博客园  阅读(996)  评论(0编辑  收藏  举报

导航