javascript中鼠标有截断现象(进入上层元素,没进入下层元素)解决方案

例 12.2  onmousemove事件
马克- to-win:马克 java社区:防盗版实名手机尾号: 73203。
马克-to-win:本例子中两个元素,不是嵌套重合元素(参见第10节),所以事件肯定先进入上层元素,所以鼠标有截断现象(进入上层元素,没进入下层元素)解决方案见下面一个例子。

<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<div id="divtest" style="position:absolute;width:300px;height:300px;background:#999;">
</div>



<div id="img" style=" z-index:1; position:absolute; width:0px; height:0px; left:0px;top:0px"><img src="1.jpg" /></div>

<script>
    var car = document.getElementById("img");

    function move(event)
    {
        var event = event || window.event;
        car.style.left =  event.clientX ;
        car.style.top =  event.clientY;
    }
    document.getElementById("divtest").onmousemove=move;
</script>




例 12.2_b
马克-to-win:本例通过事件派发解决上个例子的问题。

<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<div id="divtest" style="position:absolute;width:300px;height:300px;background:#999;">
</div>



<div id="img" style=" z-index:1; position:absolute; width:0px; height:0px; left:0px;top:0px"><img src="1.jpg" /></div>

<script>
    var car = document.getElementById("img");
    var myEventx;
    var myEventy;
    function move(event)
    {
    
        var event = event || window.event;
  //   alert("move");
/*你会发现,除正常以外,当dispatchEvent时,event.clientX总为undefined,所以提前就得myEventx=event.clientX;*/
   //      alert("ok"+"event.clientX is "+event.clientX);
        if(event.clientX==undefined) event.clientX=myEventx;
        if(event.clientY==undefined) event.clientY=myEventy;
        car.style.left =  event.clientX ;
        car.style.top =  event.clientY;
    }
  
  
        function move1(event)
    {
           var t = document.getElementById('divtest')
            var event = event || window.event;
       //     alert("ok11111"+"event.clientX is "+event.clientX);
/*下面两句话是dispatchEvent时才用到。*/     
详情请见:http://www.mark-to-win.com/membership.html
            {
                var evt = document.createEvent('HTMLEvents');
                evt.initEvent('mousemove', true, true);
                t.dispatchEvent(evt);
            }
    }

          
    document.getElementById("divtest").onmousemove=move;
    document.getElementById("img").onmousemove=move1;
</script>