为什么当子元素悬停时会触发mouseout?

时间:2010-11-04 02:30:48

标签: javascript

奇迹是鼠标光标越过子节点时触发的mouseout事件。如果游标还没有离开父节点,为什么会这样?请考虑一下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title></title>
<script type='text/javascript'>

    function someFunc(obj) {
        document.getElementById('info').innerHTML = 'over';
        document.getElementById('info3').innerHTML = 'over';

        obj.onmouseout = function() { 
            document.getElementById('info2').innerHTML = 'out';
            document.getElementById('info3').innerHTML = 'out';
        }

        if (!obj.theChild) {
            var theChild = document.createElement('div');
            theChild.style.position = 'relative';
            theChild.style.left = '20px';
            theChild.style.top = '20px';
            theChild.style.width = '40px';
            theChild.style.height = '40px';
            theChild.style.background = '#eeee00';
            obj.theChild = theChild;
            obj.appendChild(theChild);
        }
    }

</script> 
<head>
<body>

    <span id="info"></span> <span id="info2"></span> <span id="info3"></span>

    <div style="position:absolute;top:100px;left:100px;width:100px;height:100px;background:#000000;" onmouseover="someFunc(this);"></div>

</body>
</html>

2 个答案:

答案 0 :(得分:2)

答案 1 :(得分:2)

每个事件(除非你停止它的传播)都会冒泡到父元素。因此,当鼠标光标离开子元素时,会在其上生成onmouseout事件,但它未处理,因此它将传播到父元素并触发它的事件处理程序。

相关问题