本文实例为大家分享了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);
  };
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
                                免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
                                如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
                            
                        暂无“js实现鼠标滑动到某个div禁止滚动”评论...
                                    更新动态
2025年10月31日
                                2025年10月31日
                    - 小骆驼-《草原狼2(蓝光CD)》[原抓WAV+CUE]
- 群星《欢迎来到我身边 电影原声专辑》[320K/MP3][105.02MB]
- 群星《欢迎来到我身边 电影原声专辑》[FLAC/分轨][480.9MB]
- 雷婷《梦里蓝天HQⅡ》 2023头版限量编号低速原抓[WAV+CUE][463M]
- 群星《2024好听新歌42》AI调整音效【WAV分轨】
- 王思雨-《思念陪着鸿雁飞》WAV
- 王思雨《喜马拉雅HQ》头版限量编号[WAV+CUE]
- 李健《无时无刻》[WAV+CUE][590M]
- 陈奕迅《酝酿》[WAV分轨][502M]
- 卓依婷《化蝶》2CD[WAV+CUE][1.1G]
- 群星《吉他王(黑胶CD)》[WAV+CUE]
- 齐秦《穿乐(穿越)》[WAV+CUE]
- 发烧珍品《数位CD音响测试-动向效果(九)》【WAV+CUE】
- 邝美云《邝美云精装歌集》[DSF][1.6G]
- 吕方《爱一回伤一回》[WAV+CUE][454M]
 
                         
                        