一、兼容电脑端的禁止通过 ctrl + +/- 和 ctrl + 滚轮 对页面进行缩放
const keyCodeMap = {
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) {
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 });
四、完整代码示例
window.onload = function () {
const keyCodeMap = {
61: true,
107: true,
109: true,
173: true,
187: true,
189: true,
};
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) {
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 });
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();
});
};