如何在 HTML 中禁用 Ctrl+滚轮缩放?

如何在 HTML 中禁用 Ctrl+滚轮缩放?

如何在 html 中禁用 ctrl+滚轮缩放

HTML 中,您无法通过 resize 事件禁用 Ctrl+滚轮缩放,因为该事件与窗口大小调整有关。以下是如何使用 JavaScript 禁用缩放:

PC 端(原生)

document.addEventListener('mousewheel', function (e) {
  e = e || window.event;
  if ((e.wheelDelta && event.ctrlKey) || e.detail) {
    event.preventDefault();
  }
}, { capture: false, passive: false});

document.addEventListener('keydown', function (event) {
  if ((event.ctrlKey === true || event.metaKey === true)
    && (event.keyCode === 61 || event.keyCode === 107
      || event.keyCode === 173 || event.keyCode === 109
      || event.keyCode === 187 || event.keyCode === 189)) {
    event.preventDefault();
  }
}, false);

Vue 页面

methods: {
  keepRatio() {
    let ratio = 0; // 定义缩放比例
    let screen = window.screen; // 获取窗口对象
    let ua = navigator.userAgent.toLowerCase();
    if (window.devicePixelRatio !== undefined) {
      ratio = window.devicePixelRatio; // 像素大小的比例
    } else if (ua.indexOf('msie')) {
      if (screen.deviceXDPI && screen.logicalXDPI) {
        ratio = screen.deviceXDPI / screen.logicalXDPI;
      }
    } else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
      ratio = window.outerWidth / window.innerWidth; // 外部比例/内部比例:缩放比例
    }
    if (ratio) {ratio = Math.round(ratio * 100)}
    this.ratio = (ratio / 100).toFixed(2);
    document.body.style.zoom = 1 / this.ratio;  // 窗口视图除以缩放比例:即缩放还原
  }
}
mounted() {
  this.keepRatio()
  window.addEventListener('resize', () => { // 监听窗口缩放
   this.keepRatio()
  });
}

以上就是如何在 HTML 中禁用 Ctrl+滚轮缩放?的详细内容,更多请关注其它相关文章!