阻止页面被放大缩小

这段代码主要用于在网页中处理设备的屏幕适配,特别是针对PC和移动设备。它引入了Vue.js库,定义了handleScreen函数来调整body的zoom属性,detectZoom函数用于检测设备的像素比。此外,adaptive函数判断设备类型并添加相应CSS类,stopZoom函数则阻止了键盘和鼠标滚轮的缩放操作。
摘要由CSDN通过智能技术生成

将以下代码写入js文件,引入页面即可

import Vue from 'vue'
function handleScreen() {
  const m = detectZoom();
  // document.body.style.zoom = 100 / Number(m);
  document.body.style.zoom = 1;
}
function detectZoom() {
  let ratio = 0,
  screen = window.screen,
  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);
  }
return ratio;
}
function adaptive() {
  if (/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
    Vue.prototype.isPc = false;
  } else {
    Vue.prototype.isPc = true;
  }
  if (Vue.prototype.isPc) {
    handleScreen();
    document.body.setAttribute("class", "isPc")
  } else {
    document.body.setAttribute("class", "isMobile")
  }
}
function stopZoom() {
  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 });
}
// adaptive()
handleScreen()
stopZoom()
// window.onresize = function () {
//     adaptive()
// }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值