<div style="300px; height:300px; border:1px solid red;"> <div id="target"><div><span>测试</span></div></div> </div>
<style type="text/css"> #target{ 200px; height: 200px; background: #EEE;} #target div{ 150px; height: 150px; border:1px solid orange;} #target span{ display: block; 50px; height: 50px; background: gray;} </style>
var target = document.getElementById('target'); if(target.addEventListener){ target.addEventListener("mouseout",mouseoutHander,false) }else if(target.attachEvent){ target.attachEvent("onmouseout",mouseoutHander); }else{ target.onmouseout = mouseoutHander; } function mouseoutHander(e){ e = e || window.event; var target = e.target || e.srcElement; // 判断移出鼠标的元素是否为目标元素 if (target.id !== 'target') { return; } // 判断鼠标是移出元素还是移到子元素 var relatedTarget = e.relatedTarget || e.toElement; while (relatedTarget !== target && relatedTarget.nodeName.toUpperCase() !== 'BODY') { relatedTarget = relatedTarget.parentNode; } // 如果相等,说明鼠标在元素内部移动 if (relatedTarget === target) { return; } // 执行需要操作 alert('鼠标移出'); }
执行以上代码,鼠标在指定区域移动就不会一直弹出警告框