在Div中包含的元素移动时,触发div的onmouseout事件.解决方案!


我们在做显示隐藏层时,需要使用到onmouseover、onmouseout事件。
问题如下,当层中包含其它元素时,例如层中包含若干个子层,
<div id="dvroot">
      <div id="dvsub1"></div>
      <div id="dvsub1"></div>
</div>
鼠标从dvroot的空白区域,移动到dvsub层中时,我们的要求是dvroot层继续显示,但是,在移动到dvsub时,触发了onmouseout的事件,这时dvroot就会隐藏。针对该问题,在网上搜索了一个完美的解决方案,现记录下来。

以下是做的demo示例,在IE、FF下测试通过。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>javascript div mouseout-hidden-zone</title>

<script>
(function (bool) {
//兼容FF一些方法
    var html;
   
    if (bool) {
   
        html = window.HTMLElement.prototype;
       
        window.__defineGetter__("event", function () {
        //兼容Event对象
            var o = arguments.callee;
           
            do {
           
                if (o.arguments[0] instanceof Event) return o.arguments[0];
           
            } while (o = o.caller);
           
            return null;
       
        });
       
        Event.prototype.__defineGetter__("fromElement", function () {
            return this.relatedTarget;
        });
       
        html.contains = function (o) {
            do {
                if (o == this) return true;
            } while (o = o.parentNode);
            return false;
        };
       
    }
 
})(/Firefox/.test(window.navigator.userAgent));

function hitOneMoreTime(){
  var dvBox = document.getElementById("dvBox");
  
  dvBox.style.display = '';
  dvBox.onmouseout = function(){
   var dvBox = this, e = window.event;
   if(!dvBox.contains(e.toElement || e.fromElement))
   {
    dvBox.style.display = 'none';
   }
  }
 }
</script>
</head>
<body>
<div style="width: 80px; height:30px;border: solid 1px #000;" onclick="hitOneMoreTime()">Click</div>
<div id="dvBox" style="display:none;text-align:center; width: 500px; height:500px; border: solid 1px #d7d; ">
<div><img src='http://www5.mydavinci.com/x/2092/ST' /></div>
</div>
</body>
</html>

 希望对遇到这个问题的朋友有帮助。

posted @ 2009-08-06 13:36  李帅斌-Memory  阅读(3073)  评论(0编辑  收藏  举报