实现响应式web网页ctrl+鼠标滚轮等比缩放的js代码

使用非固定像素单位开发的响应式网页,如rem、vw等,使用ctrl+鼠标滚轮缩放时网页不会缩小,因为rem、vw大多会浏览器窗口宽度分辨率绑定,而ctrl+鼠标滚轮缩小,分辨率反应变化,所以网页不会等比缩小。但可以通过js+缩放比率来实现ctrl+鼠标滚轮等比缩小的效果,适用于使用了vw单位或者rem单位。

代码:

(function (doc, win) {
    var docEl = doc.documentElement,
        resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
        recalc = function () {
            var lastClientWidth = docEl.clientWidth;
            //var lastDevicePixelRatio = lastClientWidth > 1280 ? window.devicePixelRatio : 1;
            var lastDevicePixelRatio = window.devicePixelRatio < 1 ? window.devicePixelRatio : 1;
            if (!lastClientWidth) return;            
            if(lastClientWidth>1280){
                docEl.style.fontSize = 100 * (lastClientWidth / 1920 * lastDevicePixelRatio) + 'px';
            }else if(lastClientWidth > 1024){
                docEl.style.fontSize = 100 * (lastClientWidth / 1280 * lastDevicePixelRatio) + 'px';
            }else if(lastClientWidth > 750){
                docEl.style.fontSize = 100 * (lastClientWidth / 1024 * lastDevicePixelRatio) + 'px';
            }else{
                docEl.style.fontSize = 150 * (lastClientWidth / 750 * lastDevicePixelRatio) + 'px';
            }
        };
    if (!doc.addEventListener) return;
    win.addEventListener(resizeEvt, recalc, false);
    doc.addEventListener('DOMContentLoaded', recalc, false);
})(document, window);

代码中1280、1024、750分辨率下html的font-size大小根据需求调整。