1、项目中遇到的需求:鼠标进入某个元素,有个小简介,所以在鼠标停留位置需要显示一个弹出框。我绑定的是mouseenter 和 mouseleave事件,鼠标进入元素显示弹出框,离开元素隐藏弹出框。但是鼠标进入元素,在元素里面滑动的时候,弹出框会不停的闪现,特别是鼠标从元素左上角往右下角方向滑动时,弹出框闪现的更厉害。
2、自己上网搜的时候,很多都是说mouseenter和mouseover、mouseleave和mouseout的区别,我懂它们之间的区别,我觉得此bug应该与这个无关吧?
3、上代码,求大神给与解答疑惑,谢谢了~~~
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>悬停弹出框</title>
<style>
#contain{position: relative;}
#d1,#d2{
width:50px;
height:50px;
background:pink;
position:absolute;
text-align:center;
line-height:50px;
top:200px;
left:400px;
}
#d2{background:lightblue;left:700px;}
#popupBox{
width:200px;
height:200px;
border:1px solid #000;
background:#ddd;
position:absolute;
display:none;
}
</style>
</head>
<body>
<div id="contain">
<div id="d1">1</div>
<div id="d2">2</div>
</div>
<!-- 弹出框 -->
<div id="popupBox"></div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
//获取鼠标位置
function mouseCoords(e){
e= e || window.event;
if(e.pageX || e.pageY){
return {x:e.pageX, y:e.pageY};
} else{
return {
x:e.clientX + document.body.scrollLeft - document.body.clientLeft,
y:e.clientY + document.body.scrollTop - document.body.clientTop
}
}
}
// 绑定事件
$("#contain").on("mouseenter","div",function(e){
$("#popupBox").show();
var mousePos = mouseCoords(e);
$("#popupBox").css({
"top":mousePos.y,
"left":mousePos.x
})
}).on("mouseleave","div",function(){
$("#popupBox").hide();
});
</script>
</body>
</html>