Fork me on GitHub

wmode为opaque或transparent不支持鼠标滚轮的解决

原创文章,未经允许,请勿转载

在chrome等浏览器会有这个问题, 需要在html页面用js捕捉滚轮事件,然后传入到flash里面,难点是到flash之后该怎么办,我这里采用类类似冒泡的方式来触发事件。

js代码,参考自://www.denisdeng.com/?p=685

function wheel(obj, fn ,useCapture){ 
  var mousewheelevt=(/Firefox/i.test(navigator.userAgent))? "DOMMouseScroll" : "mousewheel" 
  //FF doesn't recognize mousewheel as of FF3.x 
  if (obj.attachEvent) 
  //if IE (and Opera depending on user setting) 
  obj.attachEvent("on"+mousewheelevt, handler, useCapture); 
  else if (obj.addEventListener) 
  //WC3 browsers 
  obj.addEventListener(mousewheelevt, handler, useCapture); 
  function handler(event) { 
    var delta = 0; 
    var event = window.event || event ; 
    var delta =  event.detail ?  -event.detail/3 : event.wheelDelta/120; 
    if (event.preventDefault) 
    event.preventDefault(); 
    event.returnValue = false; 
    return fn.apply(obj, [event, delta]); 
  } 
} 

function addMouseWheelListener(){ 
  var target = document.getElementById('flashobjID'); 
  wheel(target,callWheel); 
} 

function callWheel(e,delta) { 
  var target = document.getElementById('flashobjID'); 
   if(target!=undefined && target && target.fireWheel) 
     { 
                 //调用flash的方法 
         target.fireWheel(delta);   
     } 
} 

//页面加载完,附近鼠标事件侦听 
window.onload = addMouseWheelListener;

flash代码:

ExternalInterface.addCallback('fireWheel', function(delta:int):void{ 

  //获取当前鼠标下面的所有对象 
  var arr:Array = stage.getObjectsUnderPoint(new Point(stage.mouseX, stage.mouseY)); 
  if (arr.length == 0) return; 
  //只找最接近鼠标的那一层来触发就好了,底下的挡住了不管 
  var obj:DisplayObject = arr[arr.length-1]; 
  //从叶子节点,一层一层往根上找 
  while (true) 
  { 
    if (obj is InteractiveObject) 
    { 
      var intobj:InteractiveObject = obj as InteractiveObject; 

      if (intobj is TextField) 
      { 
        //TextField似乎不接受外部触发的滚轮事件,只能暴力 
        if ((intobj as TextField).mouseEnabled) 
        { 
          (intobj as TextField).scrollV -= delta; 
        } 
      } 
      else if (obj.hasEventListener(MouseEvent.MOUSE_WHEEL)) 
      { 
        var me:MouseEvent = new MouseEvent(MouseEvent.MOUSE_WHEEL, false, false, 0, 0, intobj); 
        me.delta = delta; 
        obj.dispatchEvent(me); 
      } 
    } 
    if (obj == stage || (!obj.parent)) 
    { 
      break; 
    } 
    obj = obj.parent; 
  } 

});

来源:悠游悠游,原文地址:https://yymmss.com/p/206.html