jQuery 悬停:淡入隐藏的 div,同时淡出“默认”div
题
我有两个 div(其中一个用 CSS 隐藏),它们在悬停时在公共空间内交替淡入和淡出。
这是标记:
<div id="wrap">
<div class="image">
<img src="http://domain.com/images/image.png">
</div>
<div class="text hide">
<p>Text text text</p>
</div>
</div>
我正在应用这个 jQuery 代码来淡出图像 - 并在悬停时淡入文本:
<script type="text/javascript">
$(function(){
$('#wrap').hover(
function(){
$('#wrap .image').fadeOut(100, function(){
$('#wrap .text').fadeIn(100);
});
},
function(){
$('#wrap .text').fadeOut(100, function(){
$('#wrap .image').fadeIn(100);
});
}
);
});
</script>
但问题是文本 div 会粘住并且不会淡出 - 总是鼠标移动太快。
你知道在哪里可以解决这个问题吗?
我设置了在线测试: http://paragraphe.org/stickytext/test.html
感谢您的任何提示
解决方案
如果您的包装没有宽度和高度上你可能会得到一些奇怪的结果,因为它一旦缩小图像元素被删除。要查看,添加边框和固定高度/宽度周围的包装。或至少使用相同的高度的图像和文本的div。
<style type="text/css">
#wrap { width: 200px; height: 200px; border: 1px solid black; }
</style>
EDITED
删除的代码示例并不适用于你要完成的任务。
其他提示
尝试使用 .stop()在悬停输出功能,这将防止竞争条件,你快速将鼠标移到的div
<script type="text/javascript">
$(function(){
$('#wrap').hover(
function(){
$('#wrap .image').fadeOut(100, function(){
$('#wrap.text').fadeIn(100);
});
},
function(){
$('#wrap.text').stop().fadeOut(100, function(){
$('#wrap.image').stop().fadeIn(100);
});
}
);
});
</script>
尝试使用队列:
<script type="text/javascript">
$(function(){
$('#wrap').hover(
function(){
$('#wrap .image').stop(true).fadeOut(100);
$('#wrap .image').queue(function(){
$('#wrap.text').fadeIn(100);
$(this).dequeue();
});
},
function(){
$('#wrap .image').stop(true).queue(function(){
$('#wrap.text').fadeOut(100);
$(this).dequeue();
});
$('#wrap .image').fadeIn(100);
}
);
});
</script>
在jQuery的队列每个元素,所以我想在这里做的是推出去图像队列下的文字效果。
让我给你一个建议。如果你的意图是各种图像使用类,而不是ID来应用这个效果。
...
$('.wrap').hover(
function(){
var wrap = this;
$('.image', wrap).stop(true).fadeOut(100);
$('.image', wrap).queue(function(){
$('.text', wrap).fadeIn(100);
$(this).dequeue();
});
....
这样,你只需要一次调用它。
您的代码永远不会淡出文字股利。悬停事件这两种功能将淡出图像,并在文本褪色。
您有两个hover
相同功能的代码。你是不是应该更换选择在第二种情况下?
<script type="text/javascript">
$(function(){
$('#wrap').hover(
function(){
$('#wrap .image').fadeOut(100, function(){
$('#wrap.text').fadeIn(100);
});
},
function(){
$('#wrap.text').fadeOut(100, function(){
$('#wrap.image').fadeIn(100);
});
}
);
});
</script>
感谢所有的提示 :
我尝试使用 mouseenter / mouseleave 事件,因为它们似乎详细查找它们正在处理的 div(如这里所见),但没有任何改变。因此,看到所有常用的 jQuery 指令都没有响应,我已经按照 CSS 的建议进行了检查。
这就是窍门。
我有什么:
.text p{position:relative; top:-370px; padding: 0 10px}
设置一个巨大的空白空间,浏览器将其解释为光标“未保持静止”(我注意到飞越该空白空间使文本能够正确响应)。
所以我改变了:
.text {margin-top:-370px; padding: 0 10px; float:left}
这让“p”标签单独存在,并将第二个块放置在 div 中,但后面没有任何空白空间。
然后,关于片段,它也适用于 鼠标输入 / 鼠标离开 和 徘徊 :
<script type="text/javascript">
$(function(){
$('#wrap').mouseenter(
function(){
$('#wrap .image').fadeOut(100, function(){
$('#wrap .text').fadeIn(100);
});
}
);
$('#wrap').mouseleave(
function(){
$('#wrap .text').fadeOut(100, function(){
$('#wrap .image').fadeIn(100);
});
}
);
});
</script>