阻止pc端浏览器缩放js代码

时间:2021-11-13 17:47:23

阻止pc端浏览器缩放js代码

众所周知:移动端页面禁止用户缩放界面只需加上<meta name="viewport" content="user-scalable=0"> 即可,但是pc端确实比较麻烦,用户可以通过如下几种方式来缩放:

windows:

  1. ctrl + +/-
  2. ctrl + 滚轮
  3. 浏览器菜单栏

mac:

  1. cammond + +/-
  2. 浏览器菜单栏

由于浏览器菜单栏属于系统软件权限,没发控制,我们着手解决ctrl/cammond + +/- 或 Windows下ctrl + 滚轮 缩放页面的情况,只能通过js来控制了

Reference:

*关于组织缩放的代码:http://*.com/questions/27116221/prevent-zoom-cross-browser

jquery event.whick源码,先取charCode(mdn说明其已被废弃)再取keyCode: https://github.com/jquery/jquery/blob/master/src/event.js#L633

下面是用juery和原生js实现的代码:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>img</title>
</head>
<body>
<div class="wrap"></div> <p>test测试test测试test测试test测试</p> <script src="https://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
<script>
/**
* @file 禁止pc浏览器使用ctrl/cammond + +/- 或 Windows下ctrl + 滚轮 缩放页面 (prevent borwser zoom)
* 众所周知:移动端页面禁止用户缩放界面只需要在<meta name="viewport" content="user-scalable=0"> 即可,但是pc端确实比较麻烦,只能通过js来控制了
* @author yangzongjun
* @date 2017-01-06
*/ /**
代码中event.whick的数字代号的意思:
mac下
chrome:
- 189
+ 187 ff:
- 173
+ 61 然后剩余的两个代号是107、109代表的是数字键盘的+-号
*/ // jqeury version
// $(document).ready(function () {
// // chrome 浏览器直接加上下面这个样式就行了,但是ff不识别
// $('body').css('zoom', 'reset');
// $(document).keydown(function (event) { // if ((event.ctrlKey === true || event.metaKey === true)
// && (event.which === 61 || event.which === 107
// || event.which === 173 || event.which === 109
// || event.which === 187 || event.which === 189))
// {
// event.preventDefault();
// }
// }); // $(window).bind('mousewheel DOMMouseScroll', function (event) {
// if (event.ctrlKey === true || event.metaKey) {
// event.preventDefault();
// } // });
// }); // 原生js来实现,避免依赖jquery。需要注意的是:addEventListener/DOMContentLoaded在ie中是只支持>=ie9的,一般足够了
document.addEventListener('DOMContentLoaded', function (event) {
// chrome 浏览器直接加上下面这个样式就行了,但是ff不识别
document.body.style.zoom = 'reset';
document.addEventListener('keydown', function (event) {
if ((event.ctrlKey === true || event.metaKey === true)
&& (event.which === 61 || event.which === 107
|| event.which === 173 || event.which === 109
|| event.which === 187 || event.which === 189))
{
event.preventDefault();
}
}, false);
document.addEventListener('mousewheel DOMMouseScroll', function (event) {
if (event.ctrlKey === true || event.metaKey) {
event.preventDefault();
}
}, false);
}, false); </script>
</body>
</html>

此次收获:

  1. 键盘事件的修饰键(ctrlKey、metaKey)、每个按键的编号
  2. DOMContentLoaded(dom结构渲染完成) 和 Loaded(页面中所有的资源包括图片都渲染完成) 事件的区别
  3. addEventListener 和 DOMContentLoaded 支持 >= ie9,基本无需考虑兼容性