常用的pc端網站適配方案是什麼?用的最多的大概就是父元素按照設計圖的寬度進行固定寬度,margin:0 auto居中,兩邊留白。但是有的設計圖不適合這樣兩邊留白的適配方案。
最近接手了一個pc端的項目,雖然按照常用的柵格佈局+postcss-pxtorem插件對px轉換的方法對頁面做了適配,使頁面無論在pc端打開還是在移動端打開都能自適應,但是在高清分辨率下的頁面比如5k高清,佈局還是有些亂了,這是因為px轉換成rem所依賴的根目錄字號沒有調整好,於是上網百度了很多方案參考,重新調整了適配方案,但是在移動端打開的時候佈局會亂掉,因為px的計算是根據pc端的寬高來計算的
1.刪掉html的
<meta name="viewport" content="width=device-width,height=device-height,user-scalable=no" />
刪掉這個標籤,在移動端打開的時候,佈局整體不會亂,但是子元素間距、寬高還是會和設計圖有差距
2.下載依賴:npm install --save-dev postcss-pxtorem
在vue.config.js引入依賴:
const pxtorem = require("postcss-pxtorem");//px轉換為rem插件
const autoprefixer = require("autoprefixer");//瀏覽器前綴處理工具
modules.exports={
css: {
loaderOptions: {
postcss: {
plugins: [
pxtorem({
rootValue: 100,
propList: ["*"]
}),
autoprefixer()
]
}
}
}
}
3.我在src/assets/js目錄下新建pc.js文件,在main.js裏導入這個文件
//pc.js
//設計圖紙為1366*798
function pagePc(){
let rootValue = 100;
let pc = rootValue / 1366; // 表示1366的設計圖,使用100px的默認值
let width = window.innerWidth; // 當前窗口的寬度
let height = window.innerHeight; // 當前窗口的高度
let rem = "";
let currentHeight = (width * 798) / 1366;
if (height < currentHeight) {
// 當前屏幕高度小於應有的屏幕高度,就需要根據當前屏幕高度重新計算屏幕寬度
width = (height * 1366) / 798;
}
rem = width * pc; // 以默認比例值乘以當前窗口寬度,得到該寬度下的相應font-size值
document.documentElement.style.fontSize = rem + "px";
}
pagePc();
window.onresize = function() {
pagePc();
};