首页 新闻 赞助 找找看

mouseover事件多次显示

0
悬赏园豆:30 [已解决问题] 解决于 2014-12-01 15:01

当我鼠标移动到图片时,text字体显示了两次,我只想当我鼠标移动到图片时字体显示,移出时字体隐藏,应该如何做?

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<style type="text/css">
.pics{
position: relative;
top: 200px;
left: 200px;
}
.txt{
position: absolute;
background-color: rgba(24,56,234,0.25);
width: 550px;
height: 340px;
border: 1px gray solid;
top:0;
left: 0;
}

h1{
color: #fff;
}

.txt h1{
margin-top: 100px;
}
</style>

<script type="text/javascript">
$(document).ready(function(){
$(".txt").hide();
var flag = false;

$('img').mouseover(
function(){
if(flag == false){
$(".txt").fadeIn('slow');
flag = true;
}
}
)

$('img').mouseout(
function(){
if(flag == true){
$(".txt").fadeOut('slow');
flag = false;
}
}
)
})
</script>
</head>
<body>
<div class="pic_txt">
<div class="pics">
<img src="./link.jpg"></img>//////////////////
<div class="txt">
<span><h1>This is a picture.</h1></span>
</div>
</div>
</div>
</body>
</html>

timerainbow的主页 timerainbow | 初学一级 | 园豆:21
提问于:2014-12-01 09:30
< >
分享
最佳答案
1

你这个绝对不是楼上说的hover就能解决的,因为你这个并没有发生冒泡,告诉你原因啊:你这个是由于.txt元素引起的,你想啊,你鼠标悬浮到img上,.txt元素出现了,这时你的鼠标就从图片移动到了.txt元素上,这样就触发img的mouseout事件和.txt的mouseover事件,然而img的mouseout事件触发后隐藏了.txt元素,这样鼠标又从.txt元素移动到了图片上,触发了.txt元素的mouseout事件和img的mouseover事件,我写了测试给你截图看看

我们不移动鼠标而让图片一像素一像素的移动到鼠标下面就会看到,先触发了img的mouseover事件,其它什么事件都没有发生,就显示了.txt元素,然后再移动一像素你就会发现发生了img的mouseout事件》.txt的mouseover事件》.txt的mouseout事件》img的mouseover事件,这一系统事件的触发就会先隐藏.txt元素再显示.txt元素,由于鼠标移动的快,所以我们看到的是闪了两次,你慢慢地一直移动鼠标就会一直闪动。

解决方法就是img触发mouseover,.txt触发mouseout就可以了,但是mouseover和mouseout组合会冒泡,所以建议你选择mouseenter和mouseleave的组合。

 1 $('.txt').mouseleave(
 2             function() {
 3                 $(".txt").fadeOut(0);
 4             }
 5         );
 6         $('img').mouseenter(
 7             function() {
 8                 $(".txt").fadeIn(0);
 9             }
10         )
收获园豆:30
小乔布斯 | 菜鸟二级 |园豆:446 | 2014-12-01 14:02

嗯嗯,谢谢~~

timerainbow | 园豆:21 (初学一级) | 2014-12-01 15:01

@timerainbow: 不客气,解决办法是对的,但是我的解释还是有一点问题,最近我也在找更加详细的解释,找到了,再来回复你。

小乔布斯 | 园豆:446 (菜鸟二级) | 2014-12-02 09:05
其他回答(3)
0

hover css

刘宏玺 | 园豆:14020 (专家六级) | 2014-12-01 09:53
0

$("img").hover(function(){$(".txt").fadeIn("slow");},function(){$(".txt").fadeOut("slow");});

骑着蜗牛耍流氓 | 园豆:135 (初学一级) | 2014-12-01 09:57

试过了,没用的

支持(0) 反对(0) timerainbow | 园豆:21 (初学一级) | 2014-12-01 11:16
0

楼上正解

招财圆 | 园豆:141 (初学一级) | 2014-12-01 15:01
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册