js鼠标禁止滚动 js实现鼠标滑动到某个div禁止滚动

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

js鼠标禁止滚动 js实现鼠标滑动到某个div禁止滚动

刘老实1528   2021-03-16 我要评论
想了解js实现鼠标滑动到某个div禁止滚动的相关内容吗,刘老实1528在本文为您仔细讲解js鼠标禁止滚动的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:js鼠标禁止滚动,js鼠标滚动,js鼠标滑动到某个div禁止滚动,下面大家一起来学习吧。

项目中碰到一个场景就是当鼠标滑倒某个div的时候,滑动鼠标页面不再滚动。

这里主要是当鼠标滑动到该div时,监听滚轮事件并通过preventDefault()事件来阻止滚动事件,以下是例子

eg:

#wrap {
  position:absolute;
  top:200px;
  background:#000000;
  font-size: 40px;
  width:50vw;
  text-align: center;
  color: #ffffff;
  line-height: 300px;
  height:300px;
}
<div id="wrap">
 鼠标移动进入该区域,页面禁止滚动
</div>
window.onload = function () {
  for (i = 0; i < 50; i++) {
  var x = document.createElement('div');
  x.innerHTML = "test<br/>";
  document.body.appendChild(x);
  }
 
  function $(x) {
  return document.getElementById(x);
  };
  $("wrap").onmousewheel = function scrollWheel(e) {
  var sl;
  e = e || window.event;
  if (navigator.userAgent.toLowerCase().indexOf('msie') >= 0) {
   event.returnValue = false;
  } else {
   e.preventDefault();
  };
  };
  if (navigator.userAgent.toLowerCase().indexOf('firefox') >= 0) {
  //firefox支持onmousewheel
  addEventListener('DOMMouseScroll',
   function (e) {
   var obj = e.target;
   var onmousewheel;
   while (obj) {
    onmousewheel = obj.getAttribute('onmousewheel') || obj.onmousewheel;
    if (onmousewheel) break;
    if (obj.tagName == 'BODY') break;
    obj = obj.parentNode;
   };
   if (onmousewheel) {
    if (e.preventDefault) e.preventDefault();
    e.returnValue = false; //禁止页面滚动
    if (typeof obj.onmousewheel != 'function') {
    //将onmousewheel转换成function
    eval('window._tmpFun = function(event){' + onmousewheel + '}');
    obj.onmousewheel = window._tmpFun;
    window._tmpFun = null;
    };
    // 不直接执行是因为若onmousewheel(e)运行时间较长的话,会导致锁定滚动失效,使用setTimeout可避免
    setTimeout(function () {
     obj.onmousewheel(e);
    },
    1);
   };
   },
   false);
  };
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们