<script type="text/javascript">
var oHtml = document.documentElement;
getSize();
window.onresize = function(){
getSize();
};
function getSize(){
var screenWidth = oHtml.clientWidth;
if (screenWidth < 320) {
oHtml.style.fontSize = '42.6667px';
} else if(screenWidth > 750){
oHtml.style.fontSize = '100px';
}else{
oHtml.style.fontSize = screenWidth/(750/100) + 'px';
}
}
</script>
100px = 1.0rem;
上面這種情況會出現文字太小顯示瀏覽器默認文本大小的情況,以下這種處理方式個人感覺更好一點
# 關於px轉rem
## 實現功能
根據UED給出的不同分辨率設計稿,將px轉成rem
## 原理
1. 自定義html基數: font-size: 10px, 獲取clientWidth 和 分辨率
2. clientWidth < 320 || clientWidth > 750 自定義大小
其他: 根據公式:clientWidth / (分辨率 / (分辨率/html基數))
## 說明
font-size: 不推薦使用rem,會存在一定問題,可以使用@media方式解決;其他情況均可使用rem,如:width,height,line-height,margin,padding等
## 代碼
### style.css
html {
/*
10 / 16 * 100% = 62.5%
*/
font-size: 62.5%; // font-size: 10px;
}
### index.html
(function() {
var oHtml = document.documentElement;
getSize();
// 當頁面沒有刷新單屏幕尺寸發生變化時,實時自適應。例:豎屏 轉 橫屏
window.onresize = function () {
getSize();
}
function getSize() {
var screenWidth = oHtml.clientWidth;
// screenWidth < 320 || screenWidth > 750 時
/* 方法一: 通過媒體查詢 (不是一直都需要的,處理特殊情況時需要)
html{font-size: 10px}
@media screen and (max-width:320px) {html{font-size:10px}} // 設置文本font-size時,要具體到class
@media screen and (min-width:321px) and (max-width:375px){html{font-size:11px}}
@media screen and (min-width:376px) and (max-width:414px){html{font-size:12px}}
@media screen and (min-width:415px) and (max-width:639px){html{font-size:15px}}
@media screen and (min-width:640px) and (max-width:719px){html{font-size:20px}}
@media screen and (min-width:720px) and (max-width:749px){html{font-size:22.5px}}
@media screen and (min-width:750px) and (max-width:799px){html{font-size:23.5px}}
@media screen and (min-width:800px){html{font-size:25px}}
*/
// 方法二:給出不同的值
if (screenWidth < 320) {
oHtml.style.fontSize = '10px';
} else if (screenWidth > 750) {
oHtml.style.fontSize = '20px';
} else {
// 由於設計稿分辨率的不同,這里screenWidth 所除的值也會隨之修改,
// 例:當設計稿給出750像素時,oHtml.style.fontSize = screenWidth / 75 + 'px';
// 當設計稿給出375像素時
oHtml.style.fontSize = screenWidth / 37.5 + 'px';
};
}
}())