瀏覽器縮放解決方案二,解析度控制
阿新 • • 發佈:2021-12-01
由於通過zoom控制侷限性太大,所以改用監聽縮放比例的方案,配合rem技術,也可以實現對瀏覽器縮放的控制
關鍵程式碼
@media all and (-webkit-min-device-pixel-ratio: 1) { html { font-size: 14px !important; } } @media all and (-webkit-min-device-pixel-ratio: 1.09) { html { font-size: 12.7px !important; } } @media all and (-webkit-min-device-pixel-ratio: 1.24) { html { font-size: 11.2px !important; } }
由於是專案後期,所以還要配合postcss-px2rem外掛,將px轉換成rem
vue.config.js中配置postcss-px2rem
module.exports = { css: { loaderOptions: { postcss: { plugins: [ require('postcss-px2rem')({ remUnit: 16 }) // 換算的基數 ] } } } }
但只監聽縮放,當解析度變化時,樣式還會變得無法控制,於是又監聽解析度又監聽縮放,程式碼開始變得越來越複雜
後來發現,瀏覽器的放大,其實本質是解析度的縮小,那麼其他元素不變,才形成放大的效果,所以只需要監聽解析度,就可以實現對縮放效果的控制
找到常規的解析度與縮放的組合
1920解析度下
1745(110%)
1536(125%)
1280(150%)
1680解析度下
1528(110%)
1344(125%)
1120(150%)
1440解析度下
1310(110%)
1152(125%)
960(150%)
只需要監聽這些解析度,即可實現對瀏覽器縮放的監聽
去除相近的解析度,還剩下
@media all and (max-width: 1920px) and (min-width: 1747px) { html { font-size: 16px !important; } } @media all and (max-width: 1747px) and (min-width: 1681px) { html { font-size: 14.5px !important; } } @media all and (max-width: 1681px) and (min-width: 1538px) { html { font-size: 14px !important; } } @media all and (max-width: 1537px) and (min-width: 1441px) { html { font-size: 12.8px !important; } } @media all and (max-width:1441px) and (min-width: 1346px) { html { font-size: 12px !important; } } @media all and (max-width: 1346px) and (min-width: 1281px){ html { font-size: 11.26px !important; } } @media all and (max-width: 1281px) and (min-width: 1153px){ html { font-size: 10.6px !important; } } @media all and (max-width: 1153px) and (min-width: 961px){ html { font-size: 9.6px !important; } } @media all and (max-width: 961px) { html { font-size: 8px !important; } }
缺點
postcss-px2rem外掛行內式樣式無法轉換,自己寫的還好辦,引入的外掛則需要單獨去設定
chrome字型預設最小為12px,所以fontsize小於12,字型檔案不會跟著變小了
基於這兩點,這種方法對縮放效果的控制會有很多差異,如果追求100%還原,不同頁面要不斷的調整