Home > Web Front-end > HTML Tutorial > Detailed explanation of examples of dynamically setting font size on mobile terminals

Detailed explanation of examples of dynamically setting font size on mobile terminals

零下一度
Release: 2017-06-29 11:25:34
Original
1336 people have browsed it

rem origin: font size of the root element, then rem is a unit, and the unit size is determined by the size of its first-generation ancestor font-size. Now front-end coders are silently sacrificing their own health in order to see a healthy webpage on every screen, because not only do they need to know that rem is a unit, but more importantly, they need to know how to render pages at different resolutions. Very NB.

Cause of the accident:
1.px unit is very popular on PC. When looking at the mobile phone screen, MLGB, the same 12px unit is smaller. Like ants.
2. After finally adjusting it to normal on iPhone 4, when I changed to a Chrysanthemum brand phone, the MBD became unsightly.
3. I know how to use rem, but what is the appropriate font-size of html? Damn it~.

Okay, let’s solve these problems now.
Before solving the problem, please understand some things that you may not want to know (warning: if you don’t understand these, you cannot know the truth~):
1 .Physical pixel(physical pixel)
Every screen we see is composed of small particles (physical pixels) that are difficult to see with the naked eye.

2. Logical pixel
is a point in the computer coordinate system. This point represents a virtual pixel that can be used by the program (such as CSS pixel ).

3. The device pixel ratio (device pixel ratio) is referred to as DPR
Its value reflects the physical pixels and logical pixels The relationship between them, the size of the DPR of the device can be calculated using the formula:

DPR = 物理像素 / 逻辑像素
Copy after login

So after understanding the above concepts, you can know why the css says ## on the PC #font-size=12px;But it became smaller when I switched to a mobile phone? Because of DPR, brother~.
Yes, our DPR on the computer screen is 1, but the mobile phone is different. It may be 2 or 3. There are still ways to get the device DPR:
1. In JavaScript, get it through window.devicePixelRatio
2. In css , can be passed -webkit-device-pixel-ratio, -webkit-min-device-pixel-ratio and -webkit-max-device-pixel-ratioPerform media query and make some style adaptations for different DPR devices (this is only for browsers and webviews with webkit core).

I have also read a lot of articles on dynamically setting rem on the Internet. Here are a few commonly used ones:

First, use media queries to set the font-size of html:

@media screen and (min-width: 320px) {html {font-size: 14px;}
}
 
@media screen and (min-width: 360px) {html {font-size: 16px;}
}
 
@media screen and (min-width: 400px) {html {font-size: 18px;}
}
 
@media screen and (min-width: 440px) {html {font-size: 20px;}
}
 
@media screen and (min-width: 480px) {html {font-size: 22px;}
}
 
@media screen and (min-width: 640px) {html {font-size: 28px;}
}
Copy after login

Second, use js to dynamically set

!(function(doc, win) {var docEle = doc.documentElement,
        evt = "onorientationchange" in window ? "orientationchange" : "resize",
        fn = function() {var width = docEle.clientWidth;
            width && (docEle.style.fontSize = 20 * (width / 320) + "px");
        };
     
    win.addEventListener(evt, fn, false);
    doc.addEventListener("DOMContentLoaded", fn, false);
 
}(document, window));
Copy after login

I What I want to talk about is the last one, which I think is a better implementation method at present:
Use js to calculate the DPR of the current device, dynamically set it on the html tag, and dynamically set the of the html font-size, use the css selector to set the font size under different DPR according to DPR (this method is very good~)

<span style="font-size: 18px"><code>!<span class="hljs-function"><span class="hljs-keyword">function(<span class="hljs-params">win, lib) {<span class="hljs-keyword">var timer,
        doc     = win.document,
        docElem = doc.documentElement,

        vpMeta   = doc.querySelector(<span class="hljs-string">&#39;meta[name="viewport"]&#39;),
        flexMeta = doc.querySelector(<span class="hljs-string">&#39;meta[name="flexible"]&#39;),
 
        dpr   = <span class="hljs-number">0,
        scale = <span class="hljs-number">0,
 
        flexible = lib.flexible || (lib.flexible = {}); <span class="hljs-comment">// 设置了 viewport meta<span class="hljs-keyword">if (vpMeta) { <span class="hljs-built_in">console.warn(<span class="hljs-string">"将根据已有的meta标签来设置缩放比例");<span class="hljs-keyword">var initial = vpMeta.getAttribute(<span class="hljs-string">"content").match(<span class="hljs-regexp">/initial\-scale=([\d\.]+)/); <span class="hljs-keyword">if (initial) {
            scale = <span class="hljs-built_in">parseFloat(initial[<span class="hljs-number">1]); <span class="hljs-comment">// 已设置的 initialScale
            dpr = <span class="hljs-built_in">parseInt(<span class="hljs-number">1 / scale);      <span class="hljs-comment">// 设备像素比 devicePixelRatio
        }
 
    }<span class="hljs-comment">// 设置了 flexible Meta<span class="hljs-keyword">else <span class="hljs-keyword">if (flexMeta) {<span class="hljs-keyword">var flexMetaContent = flexMeta.getAttribute(<span class="hljs-string">"content");<span class="hljs-keyword">if (flexMetaContent) { <span class="hljs-keyword">var initial = flexMetaContent.match(<span class="hljs-regexp">/initial\-dpr=([\d\.]+)/),
                maximum = flexMetaContent.match(<span class="hljs-regexp">/maximum\-dpr=([\d\.]+)/); <span class="hljs-keyword">if (initial) {
                dpr = <span class="hljs-built_in">parseFloat(initial[<span class="hljs-number">1]);
                scale = <span class="hljs-built_in">parseFloat((<span class="hljs-number">1 / dpr).toFixed(<span class="hljs-number">2));
            } <span class="hljs-keyword">if (maximum) {
                dpr = <span class="hljs-built_in">parseFloat(maximum[<span class="hljs-number">1]);
                scale = <span class="hljs-built_in">parseFloat((<span class="hljs-number">1 / dpr).toFixed(<span class="hljs-number">2));
            }
        }
    } <span class="hljs-comment">// viewport 或 flexible<span class="hljs-comment">// meta 均未设置<span class="hljs-keyword">if (!dpr && !scale) {<span class="hljs-comment">// QST<span class="hljs-comment">// 这里的 第一句有什么用 ?<span class="hljs-comment">// 和 Android 有毛关系 ?<span class="hljs-keyword">var u = (win.navigator.appVersion.match(<span class="hljs-regexp">/android/gi), win.navigator.appVersion.match(<span class="hljs-regexp">/iphone/gi)),
            _dpr = win.devicePixelRatio; <span class="hljs-comment">// 所以这里似乎是将所有 Android 设备都设置为 1 了
        dpr = u ? ( (_dpr >= <span class="hljs-number">3 && (!dpr || dpr >= <span class="hljs-number">3))
                        ? <span class="hljs-number">3
                        : (_dpr >= <span class="hljs-number">2 && (!dpr || dpr >= <span class="hljs-number">2))
                            ? <span class="hljs-number">2
                            : <span class="hljs-number">1
                  )
                : <span class="hljs-number">1;
 
        scale = <span class="hljs-number">1 / dpr;
    }
 
    docElem.setAttribute(<span class="hljs-string">"data-dpr", dpr); <span class="hljs-comment">// 插入 viewport meta<span class="hljs-keyword">if (!vpMeta) {
        vpMeta = doc.createElement(<span class="hljs-string">"meta");
         
        vpMeta.setAttribute(<span class="hljs-string">"name", <span class="hljs-string">"viewport");
        vpMeta.setAttribute(<span class="hljs-string">"content",<span class="hljs-string">"initial-scale=" + scale + <span class="hljs-string">", maximum-scale=" + scale + <span class="hljs-string">", minimum-scale=" + scale + <span class="hljs-string">", user-scalable=no"); <span class="hljs-keyword">if (docElem.firstElementChild) {
            docElem.firstElementChild.appendChild(vpMeta)
        } <span class="hljs-keyword">else {<span class="hljs-keyword">var div = doc.createElement(<span class="hljs-string">"div");
            div.appendChild(vpMeta);
            doc.write(div.innerHTML);
        }
    } <span class="hljs-function"><span class="hljs-keyword">function <span class="hljs-title">setFontSize(<span class="hljs-params">) {<span class="hljs-keyword">var winWidth = docElem.getBoundingClientRect().width; <span class="hljs-keyword">if (winWidth / dpr > <span class="hljs-number">540) {
            (winWidth = <span class="hljs-number">540 * dpr);
        } <span class="hljs-comment">// 根节点 fontSize 根据宽度决定<span class="hljs-keyword">var baseSize = winWidth / <span class="hljs-number">10;
 
        docElem.style.fontSize = baseSize + <span class="hljs-string">"px";
        flexible.rem = win.rem = baseSize;
    } <span class="hljs-comment">// 调整窗口时重置
    win.addEventListener(<span class="hljs-string">"resize", <span class="hljs-function"><span class="hljs-keyword">function(<span class="hljs-params">) {
        clearTimeout(timer);
        timer = setTimeout(setFontSize, <span class="hljs-number">300);
    }, <span class="hljs-literal">false); 
     <span class="hljs-comment">// 这一段是我自己加的<span class="hljs-comment">// orientationchange 时也需要重算下吧
    win.addEventListener(<span class="hljs-string">"orientationchange", <span class="hljs-function"><span class="hljs-keyword">function(<span class="hljs-params">) {
        clearTimeout(timer);
        timer = setTimeout(setFontSize, <span class="hljs-number">300);
    }, <span class="hljs-literal">false); 
 <span class="hljs-comment">// pageshow<span class="hljs-comment">// keyword: 倒退 缓存相关
    win.addEventListener(<span class="hljs-string">"pageshow", <span class="hljs-function"><span class="hljs-keyword">function(<span class="hljs-params">e) {<span class="hljs-keyword">if (e.persisted) {
            clearTimeout(timer);
            timer = setTimeout(setFontSize, <span class="hljs-number">300);
        }
    }, <span class="hljs-literal">false); <span class="hljs-comment">// 设置基准字体<span class="hljs-keyword">if (<span class="hljs-string">"complete" === doc.readyState) {
        doc.body.style.fontSize = <span class="hljs-number">12 * dpr + <span class="hljs-string">"px";
    } <span class="hljs-keyword">else {
        doc.addEventListener(<span class="hljs-string">"DOMContentLoaded", <span class="hljs-function"><span class="hljs-keyword">function(<span class="hljs-params">) {
            doc.body.style.fontSize = <span class="hljs-number">12 * dpr + <span class="hljs-string">"px";
        }, <span class="hljs-literal">false);
    }
  
    setFontSize();
 
    flexible.dpr = win.dpr = dpr;
 
    flexible.refreshRem = setFontSize;
 
    flexible.rem2px = <span class="hljs-function"><span class="hljs-keyword">function(<span class="hljs-params">d) {<span class="hljs-keyword">var c = <span class="hljs-built_in">parseFloat(d) * <span class="hljs-keyword">this.rem;<span class="hljs-keyword">if (<span class="hljs-string">"string" == <span class="hljs-keyword">typeof d && d.match(<span class="hljs-regexp">/rem$/)) {
            c += <span class="hljs-string">"px";
        }<span class="hljs-keyword">return c;
    };
 
    flexible.px2rem = <span class="hljs-function"><span class="hljs-keyword">function(<span class="hljs-params">d) {<span class="hljs-keyword">var c = <span class="hljs-built_in">parseFloat(d) / <span class="hljs-keyword">this.rem;         <span class="hljs-keyword">if (<span class="hljs-string">"string" == <span class="hljs-keyword">typeof d && d.match(<span class="hljs-regexp">/px$/)) {
            c += <span class="hljs-string">"rem";
        }<span class="hljs-keyword">return c;
    }
}(<span class="hljs-built_in">window, <span class="hljs-built_in">window.lib || (<span class="hljs-built_in">window.lib = {}));<br/><br/></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></code>手机淘宝很多页面用的就是这种方法来适配终端的。<br/><br/><br/><br/></span>
Copy after login

The above is the detailed content of Detailed explanation of examples of dynamically setting font size on mobile terminals. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template