Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

移动端适配:rem 和 vw 方案 #2

Open
NoName4Me opened this issue May 19, 2018 · 0 comments
Open

移动端适配:rem 和 vw 方案 #2

NoName4Me opened this issue May 19, 2018 · 0 comments
Labels

Comments

@NoName4Me
Copy link
Owner

rem 方案

无它,根元素的字体大小(根元素字体大小为 1rem)。

设置 rem 与设计稿 px 的换算比例:1 rem = 100 px,这样设计稿上的 1px 就可以写成 0.01 rem了。

(function (DOC, WIN) {
    const DESIGN_WIDTH = 750, // 根据设计稿宽度来
        BASE_FONT_SIZE = 100; // 1 rem = 100 px
    let docEl = DOC.documentElement,
        resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
        function setFontSize() {
            let clientWidth = docEl.clientWidth;
            if (!clientWidth) return;
            if (clientWidth >= DESIGN_WIDTH) { // 超过了设计稿宽度,强制以设计稿来做等比缩放
                docEl.style.fontSize = BASE_FONT_SIZE + 'px';
            } else {
                docEl.style.fontSize = BASE_FONT_SIZE * (clientWidth / DESIGN_WIDTH) + 'px';
            }
        }

    if (!doc.addEventListener) return;
    WIN.addEventListener(resizeEvt, setFontSize, false);
    DOC.addEventListener('DOMContentLoaded', setFontSize, false);
})(document, window);

但是,字体一般还是保持固定大小,不缩放,所以一般使用媒体查询,比如:

@media screen and (max-width: 321px) {
    body {
        font-size:16px
    }
}

@media screen and (min-width: 321px) and (max-width:400px) {
    body {
        font-size:17px
    }
}

@media screen and (min-width: 400px) {
    body {
        font-size:19px
    }
}

vw 方案

比较复杂,见:https://www.w3cplus.com/mobile/vw-layout-in-vue.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant