div onmouseout does not work as expected

[亡魂溺海] 提交于 2019-12-13 04:19:47

问题


Text and sample code adapted from http://www.webdeveloper.com/forum/archive/index.php/t-65078.html, may not reflect actual question:

I have a div and then a div with a nested table inside it: also there is some div outside the parent div.

<div onmousemove="move()" onmouseout="out()">
  <div id="dvRep"> </div>
    <table>
        <tr><td>ITEM 1</td></tr>
        <tr><td>ITEM 2</td></tr>
        <tr><td>ITEM 3</td></tr>
        <tr><td>ITEM 4</td></tr>
        <tr><td>ITEM 5</td></tr>
    </table>
</div>

<div id="divChartPopupMenu">
    Hide me.     
</div>

Whenever i move my mouse within the div it correctly calls the move function, but the onmouseout attribute doesn't work like i thought. i thought that the out() function would only be called if you moved your mouse off the div, but out() is called whenever i move off one of the table rows. so if my mouse is on a row and i move to the next row it calls out(). i want out() to be called only when the user moves off the entire div. any ideas?

What i am trying is on out function i am hiding another div.


回答1:


i suggest you to read this article on 3 phases of javascript events.
http://www.quirksmode.org/js/events_order.html

in the function move or out, you can check if the srcElement(IE) or target(W3C) has an id called dvRep..

it should look something like this:

function out(event)
{
   event.stopPropagation(); //cancel bubbling

   ele = event.target || event.srcElement
   if (ele.id === "dvRep"){  
      //your code
   }
}



回答2:


onmouseleave is the thing that worked for me.




回答3:


It sounds like you're having issue with event bubbling.

When you hover a tr you're mouse is no longer 'in' the div - therefore when you move between them you're going tr (out) -> div (in) -> div (out) -> tr (in). That's why you're out() function is being called between tr's.

Useful reading:

  • http://www.quirksmode.org/js/events_order.html
  • http://en.wikipedia.org/wiki/DOM_Events#Common.2FW3C_events


来源:https://stackoverflow.com/questions/9094071/div-onmouseout-does-not-work-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!