App下載

實現(xiàn)html5移動端自適應(yīng)布局的方法分享!附代碼!

被風(fēng)吹過灼思 2021-08-12 10:16:09 瀏覽數(shù) (3256)
反饋

今天和大家分享個有關(guān)于“實現(xiàn)html5移動端自適應(yīng)布局的方法分享!”這方面的相關(guān)內(nèi)容,希望有在學(xué)習(xí)自適應(yīng)的小伙伴們可以在這篇文章中收獲到自適應(yīng)的相關(guān)知識!

場景:為適應(yīng)各種大小的屏幕

自適應(yīng)布局我知道的兩種方式

1.使用媒體查詢,下面制定了幾種適應(yīng)方式,例如第一個表示屏幕寬度在320px-360px之間的,html字體大小適配為13.65px

<style>
   @media only screen and (max-width: 360px) and (min-width: 320px){
    html{
     font-size:13.65px;
    }
   }
   @media only screen and (max-width: 375px) and (min-width: 360px){
    html{
     font-size:23.4375px;
    }
   }
   @media only screen and (max-width: 390px) and (min-width: 375px){
    html{
     font-size:23.4375px;
    }
   }
   @media only screen and (max-width: 414px) and (min-width: 390px){
    html{
     font-size:17.64px;
    }
   }
   @media only screen and (max-width: 640px) and (min-width: 414px){
    html{
     font-size:17.664px;
    }
   }
   @media screen and (min-width: 640px){
    html{
     font-size:27.31px;
    }
   }
  </style>

2.響應(yīng)式,獲取到屏幕的寬度,計算出一定的比例大小,使用rem代替px,在使用的時候如 font-size:1rem,在不同屏幕大小的手機上展示的大小效果是不一樣的,和手機屏幕的大小比例自適應(yīng):

<script>
   (function(doc, win) {
    var docEl = doc.documentElement, //根元素html
     //判斷窗口有沒有orientationchange這個方法,有就賦值給一個變量,沒有就返回resize方法。
     resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
     recalc = function() {
      var clientWidth = docEl.clientWidth;
      if(!clientWidth) return;
      //把document的fontSize大小設(shè)置成跟窗口成一定比例的大小,從而實現(xiàn)響應(yīng)式效果。
      if(clientWidth >= 640) {
       clientWidth = 640;
      }
      docEl.style.fontSize = 20 * (clientWidth / 320) + 'px';
      console.log(clientWidth);
      console.log(docEl.style.fontSize);
     };
     recalc();
    if(!doc.addEventListener) return;
    win.addEventListener(resizeEvt, recalc, false); //addEventListener事件方法接受三個參數(shù):第一個是事件名稱比如點擊事件onclick,第二個是要執(zhí)行的函數(shù),第三個是布爾值
    doc.addEventListener('DOMContentLoaded', recalc, false) //綁定瀏覽器縮放與加載時間
   })(document, window);
  </script>
<div id="div2" class="text" style="border: 0.04rem solid #ccc;
            height: 14rem;font-size: 0.5rem;">

那么到這里我們有關(guān)于:“實現(xiàn)html5移動端自適應(yīng)布局的方法分享!”這方面的內(nèi)容分享也結(jié)束了,更多的自適應(yīng)學(xué)習(xí)方法和資源我們都可以使用W3Cschool進行學(xué)習(xí)和了解!


0 人點贊