移動端適配JS和CSS
阿新 • • 發佈:2018-12-23
移動端適配一般是兩種方式
一JS方式:
setRem(); window.addEventListener("orientationchange", setRem); window.addEventListener("resize", setRem); function setRem() { /* * 以750*1334的設計稿為例:1rem=40px */ var html = document.querySelector("html"); var width = html.getBoundingClientRect().width; html.style.fontSize = width / 18.75 + "px"; }
JS方式書寫方便,而且適配所有的機型,但是好像會有小數點問題
二CSS方式:
/* 適配 */ @media only screen and (min-width: 320px) { html { font-size: 17.066666px !important; } } @media only screen and (min-width: 360px) { html { font-size: 19.2px !important; } } @media only screen and (min-width: 375px) { html { font-size: 20px !important; } } @media only screen and (min-width: 400px) { html { font-size: 21.33333333px !important; } } @media only screen and (min-width: 412px) { html { font-size: 21.97333px !important; } } @media only screen and (min-width: 414px) { html { font-size: 22.08px !important; } } @media only screen and (min-width: 480px) { html { font-size: 25.6px !important; } } @media only screen and (min-width: 768px) { html { font-size: 40.96px !important; } }
CSS方式適配比較麻煩,每一個機型都要去手動設定,但是比較準確,小數點問題好像會被解決掉