resize事件 + devicePixelRatio检测是否缩放实例页面

回到相关文章 »

效果:

代码:

HTML代码:
<output id="result"></output>
JS代码:
// 初始缩放比例
let originPixelRatio = localStorage.devicePixelRatio;
if (!originPixelRatio) {
    originPixelRatio = window.devicePixelRatio;
    // 整数保存
    if (Number.isInteger(originPixelRatio)) {
        localStorage.devicePixelRatio = originPixelRatio;
    }
}

let lastPixelRatio = originPixelRatio;
window.addEventListener('resize', function () {
    let currentPixelRatio = window.devicePixelRatio;

    if (currentPixelRatio !== lastPixelRatio) {
        result.innerHTML = '页面发生了缩放,缩放比例应该是:' + Math.round(1000 * (currentPixelRatio / originPixelRatio)) / 10 + '%';
    }

    lastPixelRatio = currentPixelRatio;
});

result.innerHTML = '当前缩放比例为:' +  Math.round(1000 * (window.devicePixelRatio / originPixelRatio)) / 10 + '%';