Skip to content

移动端REM适配代码

下面是一段用于移动端 REM 适配的 JavaScript 原生代码。它通过动态计算屏幕宽度并设置 HTML 根元素的 font-size,从而实现基于 REM 的自适应布局。

js
//REM适配
new function() {
    var _self = this;
    _self.width = 640; // 设置默认最大宽度
    _self.fontSize = 100; // 默认字体大小
    _self.widthProportion = function() {
        var p = (document.body && document.body.clientWidth || document.getElementsByTagName("html")[0].offsetWidth) / _self.width;
        return p > 1 ? 1 : p < 0.5 ? 0.5 : p;
    };
    _self.changePage = function() {
        document.getElementsByTagName("html")[0].setAttribute("style", "font-size:" + _self.widthProportion() * _self.fontSize + "px !important");
    }
    _self.changePage();
    window.addEventListener('resize', function() { _self.changePage(); }, false);
};

Released under the MIT License.