創建一個 position: fixed; left: 5px 的隱藏探測元素,定期檢測其 getBoundingClientRect().left 是否為 5px。若頁面被縮放,瀏覽器會按縮放比例渲染固定定位元素,導致實際像素位置偏移。
function initZoomDetector() {
// 防止重複初始化
if (document.getElementById('zoomCheck')) return;
const detector = document.createElement('span');
detector.id = 'zoomCheck';
detector.style.cssText = 'position:fixed;left:5px;top:5px;visibility:hidden;pointer-events:none;';
document.body.appendChild(detector);
let lastRatio = 1;
const checkInterval = setInterval(() => {
const rect = detector.getBoundingClientRect();
const currentLeft = Math.round(rect.left);
// 允許 1px 誤差(亞像素渲染)
if (Math.abs(currentLeft - 5) > 1) {
const zoom = currentLeft / 5; // 近似縮放比
if (Math.abs(zoom - lastRatio) > 0.05) { // 防抖
lastRatio = zoom;
showZoomWarning(zoom);
}
}
}, 2000);
// 頁面卸載清理
window.addEventListener('beforeunload', () => clearInterval(checkInterval));
}
function showZoomWarning(zoom) {
const msg = `檢測到頁面縮放:${Math.round(zoom * 100)}% (正常 100%)。\n` +
`請恢復默認縮放:\n` +
`Windows/Linux: Ctrl + 0\n` +
`Mac: Cmd + 0\n` +
`或瀏覽器菜單 → 縮放 → 重置。`;
// 避免彈窗阻塞,改用非模態提示
if (!document.getElementById('zoomToast')) {
const toast = document.createElement('div');
toast.id = 'zoomToast';
toast.style.cssText = 'position:fixed;top:20px;right:20px;background:#fff3cd;color:#856404;padding:16px 24px;border-radius:4px;box-shadow:0 4px 12px rgba(0,0,0,.15);z-index:9999;max-width:360px;font-size:14px;line-height:1.5;';
toast.innerHTML = msg.replace(/\n/g, '
') + '
';
document.body.appendChild(toast);
// 10 秒自動消失
setTimeout(() => toast.remove(), 10000);
}
}
// 頁面加載後啟動
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initZoomDetector);
} else {
initZoomDetector();
}
window.devicePixelRatio 和 screen.logicalXDPI (IE) 綜合判斷。使用 rem、vw/vh、%、clamp()、container queries 實現真正響應式佈局,**擁抱用戶縮放**而非對抗它。