mouseover 问题
一个DIV鼠标在上面移动,只要一直在范围内,只会触发一个onmouseover事件
但是假如这个DIV中还嵌套有n个子DIV,那么在这n个子DIV之间移动的时候,每跨越一次DIV就是触发一次onmouseover事件。
代码如下:
<!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><script>var times = 0;function show(){times = times+1;document.getElementById("times").innerHTML=times; }</script><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>无标题文档</title></head><body><label id="times"></label><div id="popWin" onMouseOver="show();" style="width:300px;border:50px solid #06F;height:200px;"><div id="popWin2" style="width:150px;height:200px;float:left;background:#777;"></div><div id="popWin3" style="width:150px;height:200px;float:left;background:#222;"></div></div><br/><div id="popWin4" onMouseOver="show();" style="width:300px;border:50px solid #06F;height:200px;"></div></body></html>
<!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> <script> var times = 0; function show() { times = times + 1; document.getElementById("times").innerHTML = times; } </script> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>无标题文档</title></head><body> <label id="times"> </label> <div id="popWin" onmouseover="show();" style="width: 300px; border: 50px solid #06F; height: 200px;"> <div id="popWin2" onmouseover="event.cancelBubble=true;" style="width: 150px; height: 200px; float: left; background: #777;"> </div> <div id="popWin3" onmouseover="event.cancelBubble=true;" style="width: 150px; height: 200px; float: left; background: #222;"> </div> </div> <br /> <div id="popWin4" onmouseover="show();" style="width: 300px; border: 50px solid #06F; height: 200px;"> </div></body></html>
[解决办法]
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title></head><body> <label id="times"></label> <div id="popWin" style="width:300px;border:50px solid #06F;height:200px;"> <div id="popWin2" style="width:150px;height:200px;float:left;background:#777;"></div> <div id="popWin3" style="width:150px;height:200px;float:left;background:#222;"></div> </div> <br/> <div id="popWin4" style="width:300px;border:50px solid #06F;height:200px;"> </div> <script> var times = 0, showDiv = document.getElementById("times"); document.getElementById('popWin').onmouseover = function(event){ var e = event || window.event, relatedTarget = e.relatedTarget || e.fromElement; if(!contains(this, relatedTarget)){ times = times+1; showDiv.innerHTML=times; } } function contains(elem1, elem2){ if(elem1.compareDocumentPosition){ var state = elem1.compareDocumentPosition(elem2); return state === 0 || state === 20 ? true : false; }else{ return elem1.contains(elem2); } } </script></body></html>