HTML5中 rem適配方案與 viewport 適配問題詳解
發(fā)布時間:2021-04-26 15:33:54 作者:耶溫
我要評論

這篇文章主要介紹了HTML5中 rem適配方案與 viewport 適配問題詳解,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
H5 端 rem 適配方案與 viewport 適配
rem
rem 是 CSS3 新增的一個相對單位(root em,根 em)
只根據(jù)當前頁面 HTML 頁面的 font-size 設(shè)置,如果根目錄的 font-size 為 18px,則 1rem=18px
媒體查詢設(shè)置
@media screen and (min-width: 320px) { html { font-size: 32px; } } @media screen and (min-width: 375px) { html { font-size: 37.5px; } } @media screen and (min-width: 414px) { html { font-size: 41.4px; } } @media screen and (min-width: 750px) { html { font-size: 75px; } }
使用 JS 動態(tài)修改
<script> // 根據(jù)屏幕尺寸大小調(diào)整html的fontsize function setHtmlFontSize() { const width = document.documentElement.clientWidth; document.documentElement.style.fontSize = width / 10 + "px"; } // 初始化 setHtmlFontSize(); // 監(jiān)聽屏幕尺寸變化事件 window.addEventListener("resize", setHtmlFontSize); // 監(jiān)聽屏幕翻轉(zhuǎn)事件 window.addEventListener("orientationchange", setHtmlFontSize); </script>
viewport
通過縮放來實現(xiàn)移動端各個尺寸的適配
適配方案 動態(tài)創(chuàng)建 mate viewport 屬性,根據(jù)當前屏幕尺寸動態(tài)設(shè)置縮放值
Viewport 屬性
屬性 | 說明 | 備注 |
---|---|---|
width | 以 px 為單位定義 viewport 的寬度 | 一個正整數(shù)或者額字符串 device-width |
height | 以 px 為單位定義 viewport 的高度 | 一個正整數(shù)或者額字符串 device-height |
initial-scale | 定義設(shè)備的 dips 寬度與 viewport 尺寸之間的比例 | 一個 0.0 到 10.0 之間的正數(shù) |
maximum-scale | 定義最大縮放值,他的值必需大于等于 minimum-scale 的值 | 一個 0.0 到 10.0 之間的正數(shù) |
minimum-scale | 定義最小縮放值,他的值必需小于等于 maximum-scale 的值 | 一個 0.0 到 10.0 之間的正數(shù) |
user-scalable | 一個布爾值,用戶是否可以縮放頁面 | yes 或 no |
使用 js 動態(tài)設(shè)置 viewport 屬性
原理:通過設(shè)置 viewport 的 initial-scale 相關(guān)屬性 , 將所有設(shè)備布局視口的寬度調(diào)整為設(shè)計圖的寬度
//定義設(shè)計稿寬度為375 const DESIGN_WIDTH = 375; //通過設(shè)置meta元素中content的initial-scale值達到移動端適配 const setViewport = function () { //計算當前屏幕的寬度與設(shè)計稿比例 let scale = window.screen.width / DESIGN_WIDTH; // 獲取元素 let meta = document.querySelector("meta[name=viewport]"); let content = `width=${DESIGN_WIDTH}, initial-scale=${scale}, maximum-scale=${scale}, minimum-scale=${scale}`; // 判斷是否已存在 if (!meta) { meta = document.createElement("meta"); meta.setAttribute("name", "viewport"); document.head.appendChild(meta); } meta.setAttribute("content", content); }; setViewport(); // 監(jiān)聽屏幕變化事件 window.addEventListener("resize", setViewport); // 監(jiān)聽屏幕翻轉(zhuǎn)事件 window.addEventListener("orientationchange", setViewport);
到此這篇關(guān)于HTML5中 rem適配方案與 viewport 適配問題詳解的文章就介紹到這了,更多相關(guān)html5 rem適配內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持腳本之家!
相關(guān)文章
- 這篇文章主要介紹了Html5移動端網(wǎng)頁端適配(js+rem),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習2021-02-03
- 本篇文章主要介紹了詳解html5頁面 rem 布局適配方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-01-12
html5中JavaScript removeChild 刪除所有節(jié)點
通過JavaScript可以刪除所有節(jié)點,本文里主要討論 removeChild 函數(shù),大家可以看看下面的示例2014-05-16