问题:在jQuery中,对元素绑定mouseover和mouseout事件时,每次移入移出该元素和子元素时,都会触发事件,从而会出现闪动的现象。
原因:浏览器的冒泡行为。
解决方案:
- 使用mouseenter事件和mouseleave事件分别代替mouseover事件和mouseout事件。
例如有如下代码:
<style>
div{width: 50px;height: 50px;background:#ccc;}
#test{background:red;width: 100px;height: 100px;}
</style>
<div id="test">
<div></div>
</div>
<script>
var test=document.getElementById("test");
test.addEventListener("mouseover",function(){alert("aa");})
</script>
如上代码中,当你在test中的div上移入时也会触发alert,只需把以上代码中的mouseover改为mouseenter即可解决此问题。
2.延迟执行(setTimeout)和取消执行(clearTimeout),就是当使用mouseover的时候延迟执行,当使用mouseout的时候取消延迟执行。
例如代码如下:
test.onmouseover=function(){
clearTimeout(t);
t=setTimeout(zoomIn,400);
alert("aa")
};
test.onmouseover=function(){
if(t!=null)clearTimeout(t);
t=null;
} ;