js实现禁止网页缩放(Ctrl+鼠标、+、-缩放有效亲测)

2023-08-08 14:18:15 浏览数 (2)

背景:现在是凌晨1:35我还在帮客户修改网页,要求不高但来钱快,学生党不容易啊,客户提到了很多网页的优化,其中这一条 让我头疼了许久,大家就不用踩坑了,看下面的就可以了

禁止滑轮:

代码语言:javascript复制
 window.addEventListener('mousewheel', function(event){
        if (event.ctrlKey === true || event.metaKey) {
              event.preventDefault();
        }
      },{ passive: false});

      //firefox
      window.addEventListener('DOMMouseScroll', function(event){
          if (event.ctrlKey === true || event.metaKey) {
                event.preventDefault();
          }
      },{ passive: false});

禁止 、- :

代码语言:javascript复制
window.onload = function() {
  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);
}

完整代码:

代码语言:javascript复制
<script>
//luwenjie hualun
      window.addEventListener('mousewheel', function(event){
        if (event.ctrlKey === true || event.metaKey) {
              event.preventDefault();
        }
      },{ passive: false});

      //firefox
      window.addEventListener('DOMMouseScroll', function(event){
          if (event.ctrlKey === true || event.metaKey) {
                event.preventDefault();
          }
      },{ passive: false});
// _
window.onload = function() {
  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);
}


</script>

看个轮廓就可以了哈,反正两个都不会缩放,今天就到这里!

0 人点赞