js禁用鼠标滚动wheel/DomMouseScroll

鼠标滚轮事件有兼容性问题。IE和chrome支持mousewheel事件,老版本Firefox支持DomMouseScroll。下面给出禁用鼠标滚动兼容代码。

function scrollFunc(evt) {
  evt = evt || window.event;
    if(evt.preventDefault) {
    // Firefox
      evt.preventDefault();
      evt.stopPropagation();
    } else {
      // IE
      evt.cancelBubble=true;
      evt.returnValue = false;
  }
  return false;
}
function disabledMouseWheel(obj) {
  if (document.addEventListener) {
    obj.addEventListener('DOMMouseScroll', scrollFunc, false);
  }//W3C
  obj.onmousewheel  = scrollFunc;//IE/Opera/Chrome
}
//在某个元素上禁用鼠标滚动
$('.el').each(function(){
    disabledMouseWheel(this);
});
//禁用整个窗口滚动事件
window.onload = disabledMouseWheel(this);

MSDN上有一个判断这个鼠标滚动兼容事件。

support = "onwheel" in document.createElement("div") ? "wheel" : // Modern browsers support "wheel"
              document.onmousewheel !== undefined ? "mousewheel" : // Webkit and IE support at least "mousewheel"
              "DOMMouseScroll"; // let's assume that remaining browsers are older Firefox

结合起来

function scrollFunc(evt) {
  evt = evt || window.event;
  if(evt.preventDefault) {
  // Firefox
  evt.preventDefault();
  } else {
  // IE
  evt.returnValue = false;
  }
}

function disabledMouseWheel(obj) {
  var prefix = "", _addEventListener, support;
  if ( window.addEventListener ) {
    _addEventListener = "addEventListener";
  } else {
    _addEventListener = "attachEvent";
    prefix = "on";
  }
  support = "onwheel" in document.createElement("div") ? "wheel" : // Modern browsers support "wheel"
  document.onmousewheel !== undefined ? "mousewheel" : // Webkit and IE support at least "mousewheel"
  "DOMMouseScroll"; // let's assume that remaining browsers are older Firefox
  if(support == 'DOMMouseScroll'){
    obj.addEventListener('MozMousePixelScroll', scrollFunc, false);
  }else{
    obj[ _addEventListener ]( prefix + support,function(e)
    {
      scrollFunc(e);
    })
  }
}
//在某个元素上禁用鼠标滚动
var el = document.getElementById('element');
disabledMouseWheel(el);
//禁用整个窗口滚动事件
window.onload = disabledMouseWheel(this);

目前用第一个没有问题,所以第二个代码不看也罢。。。

原创文章:js禁用鼠标滚动wheel/DomMouseScroll ,未经许可,禁止转载,©版权所有
原文出处:前端开发博客 (http://caibaojian.com/js-mousewheel-dommousescroll.html)
评论已关闭。