移动端、PC端屏幕适配

2020-12-23  本文已影响0人  谢炳南
移动端适配

页面引入ydui.flexible.js
页面布局采用rem布局
rem计算方式:设计图尺寸px / 100 = 实际rem 例: 100px = 1rem

/**
 * YDUI 可伸缩布局方案
 * rem计算方式:设计图尺寸px / 100 = 实际rem  例: 100px = 1rem
 */
!function (window) {

    /* 设计图文档宽度 */
    var docWidth = 750;

    var doc = window.document,
        docEl = doc.documentElement,
        resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize';

    var recalc = (function refreshRem () {
        var clientWidth = docEl.getBoundingClientRect().width;

        /* 8.55:小于320px不再缩小,11.2:大于420px不再放大 */
        docEl.style.fontSize = Math.max(Math.min(20 * (clientWidth / docWidth), 11.2), 8.55) * 5 + 'px';

        return refreshRem;
    })();

    /* 添加倍屏标识,安卓倍屏为1 */
    docEl.setAttribute('data-dpr', window.navigator.appVersion.match(/iphone/gi) ? window.devicePixelRatio : 1);

    if (/iP(hone|od|ad)/.test(window.navigator.userAgent)) {
        /* 添加IOS标识 */
        doc.documentElement.classList.add('ios');
        /* IOS8以上给html添加hairline样式,以便特殊处理 */
        if (parseInt(window.navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/)[1], 10) >= 8)
            doc.documentElement.classList.add('hairline');
    }

    if (!doc.addEventListener) return;
    window.addEventListener(resizeEvt, recalc, false);
    doc.addEventListener('DOMContentLoaded', recalc, false);

}(window);

移动端可以给body添加该样式

body{
    max-width: 8rem;
    margin: 0 auto;
    background: #f2f2f2;
    position: relative;
    -webkit-touch-callout:none; /*系统默认菜单被禁用*/ 
    -webkit-user-select:none; /*webkit浏览器*/ 
    -khtml-user-select:none; /*早期浏览器*/ 
    -moz-user-select:none;/*火狐*/ 
    -ms-user-select:none; /*IE10*/ 
    user-select:none; 
}
PC端适配

页面布局采用rem布局
可修改designSize的设置图大小
rem计算方式:设计图尺寸px / 100 = 实际rem 例: 100px = 1rem
适用于某些全屏页面,位置大小同等缩放

        (function(win) {
                var tid;
                function refreshRem() {
                    let designSize = 1920; // 设计图尺寸
                    let html = document.documentElement;
                    let wW = html.clientWidth;// 窗口宽度
                    let rem = wW * 100 / designSize; 
                    document.documentElement.style.fontSize = rem + 'px';
                }
            
            win.addEventListener('resize', function() {
                clearTimeout(tid);
                tid = setTimeout(refreshRem, 300);
            }, false);
            win.addEventListener('pageshow', function(e) {
                if (e.persisted) {
                    clearTimeout(tid);
                    tid = setTimeout(refreshRem, 300);
                }
            }, false);
            refreshRem();
        })(window);
上一篇 下一篇

猜你喜欢

热点阅读