兩種移動端rem布局實現方法

來源:互聯網
上載者:User
據瞭解,現在有兩種rem布局的樣式控制,其中一種是通過css的媒體查詢,另外一種是通過引入js來控制,這兩種方法各有各的優點,但是我還是喜歡用引入js的方法來實現rem布局,儘管現在市面上大多數都在使用css媒體查詢的方式實現,在此我就將這兩種方法做一總結:

方法一:常用方法,css媒體查詢

@media only screen and (max-width: 600px), only screen and (max-device-width:400px) {  html,body {    font-size:50px;  }}@media only screen and (max-width: 500px), only screen and (max-device-width:400px) {  html,body {    font-size:40px;  }}@media only screen and (max-width: 400px), only screen and (max-device-width:300px) {  html,body {    font-size:30px;  }}.box{  border: 1rem solid #000;  font-size: 1rem;}

對於這種方法而言,他僅僅通過css檔案就可以實現,在載入頁面的過程中,請求的檔案較少,但是如果使用的兩個移動端裝置螢幕寬度相差不大,都在媒體查詢所設定的同一區間,那麼頁面中的文字大小等不會變化,可是使用引入js的方法就不一樣了。

方法二:引入js

// 需求:根據設計圖的比例去動態設定不同螢幕下面對應的font-size值// 這段JS不要添加入口函數,並且引用的時候放到最前面// ui的大小根據自己的需求去改// 設計圖的寬度var ui = 750;// 自己設定的font值var font = 40;// 得到比例值var ratio = ui/font;var oHtml = document.documentElement;var screenWidth = oHtml.offsetWidth;// 初始的時候調用一次getSize();window.addEventListener('resize', getSize);// 在resize的時候動態設定fontsize值function getSize(){  screenWidth = oHtml.offsetWidth;  // 限制區間  if(screenWidth <= 320){    screenWidth = 320;  }else if(screenWidth >= ui){    screenWidth = ui;  }  oHtml.style.fontSize = screenWidth/ratio + 'px';}

這種通過引入js的方法,面對不同尺寸的移動端裝置,都能實現文字大小等尺寸的細微變化。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.