手機端適配方案 媒體查詢和flexbale

方法一  flexible
1、npm 包安裝
lib-flexible 淘寶適配方案 
px2rem px自動轉rem

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

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

3、配置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>
相關文章
相關標籤/搜索