dom事件与setTimeout


<html>
<head>
<script type="text/javascript">
function mouseout(){
alert("mouseout!!");
}

</script>
</head>
<body>
<div id="div1" onmouseout="mouseout()" style="width: 100px;height: 100px;background-color: red;">
<div style="width: 50px;height: 50px;background-color: blue;">
<a>aaaaaaaa</a>
</div>
</div>
</body>
</html>


我的目的是鼠标移到div1外面时执行事件,里面的div和a元素应和div1是一个整体,但运行时,由于事件模型的干扰,当鼠标移进里面的div或a元素时,div1的onmouseout事件也会被触发,这样就不合本意,通过下面方法可解决,再加入onmouseover事件

var timeOut;
function mouseout(){
timeOut = setTimeout(function (){
alert("mouseout!!");
},1);
}
function mouseover(){
clearTimeout(timeOut);
}




下面是网友提供的DOM事件模型测试,比较不错

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style type="text/css" media="screen">
div * {
display: block;
margin: 4px;
padding: 4px;
border: 1px solid white;
}
textarea {
width: 20em;
height: 2em;
}
</style>
<script type="text/javascript">
//<![CDATA[
function init() {
var log = document.getElementsByTagName('textarea')[0];
var all = document.getElementsByTagName('div')[0].getElementsByTagName('*');
for (var i = 0, n = all.length; i < n; ++i) {
all[i].onmouseover = function(e) {
this.style.border = '1px solid red';
log.value = '鼠标现在进入的是: ' + this.nodeName;
};
all[i].onmouseout = function(e) {
this.style.border = '1px solid white';
};
}
var all2 = document.getElementsByTagName('div')[1].getElementsByTagName('*');
for (var i = 0, n = all2.length; i < n; ++i) {
all2[i].onmouseover = function(e) {
this.style.border = '1px solid red';
if (e)//停止事件冒泡
e.stopPropagation();
else
window.event.cancelBubble = true;
log.value = '鼠标现在进入的是: ' + this.nodeName;
};
all2[i].onmouseout = function(e) {
this.style.border = '1px solid white';
};
}
}


window.onload = init;
//]]>
</script>
</head>
<body>
<p>
DOM树的结构是:
</p>
<pre><code>
UL
- LI
- A
- SPAN
</code></pre>
<div>
<ul>
<li>
<a href="#"><span>Bubbllllllllllllllle</span></a>
</li>
<li>
<a href="#"><span>Bubbllllllllllllllle</span></a>
</li>
</ul>
</div>
<textarea></textarea>
<p>
鼠标进入UL的任何一个子元素,如果不停止冒泡,我们从UL到SPAN都定义了鼠标悬停(<code>
mouseover</code>
)事件,这个事件会上升了UL,从而从鼠标所进入的元素到UL元素都会有红色的边。
</p>
<div>
<ul>
<li>
<a href="#"><span>Bubbllllllllllllllle</span></a>
</li>
<li>
<a href="#"><span>Bubbllllllllllllllle</span></a>
</li>
</ul>
</div>
<p>
如果停止冒泡,事件不会上升,我们就可以获取精确的鼠标进入元素。
</p>
</body>
</html>
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页