HTML代码:
<output id="result"></output>
JS代码:
// 初始缩放比例
let originPixelRatio = localStorage.devicePixelRatio;
if (!originPixelRatio) {
originPixelRatio = window.devicePixelRatio;
// 整数保存
if (Number.isInteger(originPixelRatio)) {
localStorage.devicePixelRatio = originPixelRatio;
}
}
let mqListener = function () {
let currentPixelRatio = window.devicePixelRatio;
result.innerHTML = '页面发生了缩放,缩放比例应该是:' + Math.round(1000 * (currentPixelRatio / originPixelRatio)) / 10 + '%';
// 移除之前的查询检测
this.removeEventListener('change', mqListener);
// 使用新的查询检测
matchMedia(`(resolution: ${currentPixelRatio}dppx)`).addEventListener('change', mqListener);
};
matchMedia(`(resolution: ${originPixelRatio}dppx)`).addEventListener('change', mqListener);
result.innerHTML = '当前缩放比例为:' + Math.round(1000 * (window.devicePixelRatio / originPixelRatio)) / 10 + '%';