js采用覆盖键、覆盖鼠标滑动事件实现禁止网页通过 ctrl + +/- 和 ctrl + 滚轮 对页面进行缩放

时间:2024-09-30 16:47:53
/** * 采用覆盖键、覆盖鼠标滑动事件;禁止通过 ctrl + +/- 和 ctrl + 滚轮 对页面进行缩放 * */ window.onload = function () { /** * 兼容电脑端的禁止通过 ctrl + +/- 和 ctrl + 滚轮 对页面进行缩放 * */ const keyCodeMap = { // 91: true, // command 61: true, 107: true, // 数字键盘 + 109: true, // 数字键盘 - 173: true, // 火狐 - 号 187: true, // + 189: true, // - }; // 覆盖ctrl||command + ‘+’/‘-’ document.onkeydown = function (event) { const e = event || window.event; const ctrlKey = e.ctrlKey || e.metaKey; if (ctrlKey && keyCodeMap[e.keyCode]) { e.preventDefault(); } else if (e.detail) { // Firefox event.returnValue = false; } }; // 覆盖鼠标滑动 document.body.addEventListener('wheel', (e) => { if (e.ctrlKey) { if (e.deltaY < 0) { e.preventDefault(); return false; } if (e.deltaY > 0) { e.preventDefault(); return false; } } }, { passive: false }); /** * 兼容iOS10以上Safari浏览器无法禁止缩放的解决方案 * */ // 阻止双击放大 var lastTouchEnd = 0; document.addEventListener('touchstart', function (event) { if (event.touches.length > 1) { event.preventDefault(); } }); document.addEventListener('touchend', function (event) { var now = (new Date()).getTime(); if (now - lastTouchEnd <= 300) { event.preventDefault(); } lastTouchEnd = now; }, false); // 阻止双指放大 document.addEventListener('gesturestart', function (event) { event.preventDefault(); }); };