我希望鼠标悬停在 coverImg 上然后显示 coverInfo
coverInfo 显示图片的标题和描述
然后显示 coverInfo
但我希望 coverInfo 在鼠标悬停在其自身上时保持并可点击
但它立即消失了。
那么我错过了什么?
HTML
<div class="workshop_img">
<div class="coverInfo"></div>
<a href="#">
<span class="coverImg" style="background-image:url('images/work/show1.jpg')" title="Chictopia "></span>
</a>
CSS:
.coverInfo {
position:absolute;
width: 200px;
height:200px;
background:rgba(0,0,0,0.5);
top:30%;
left:30%;
display:none;
}
查看jQuery代码
$(function() {
$(".coverImg").each(function() {
//make the background image move a little pixels
$(this).css({
'backgroundPosition' : "-40px 0"
}).mouseover(function() {
$(this).stop().animate({
'backgroundPosition' : " -20px -60px "
}, {
duration : 90
});
//shwo the info box
var content = $(this).attr("title");
$("<div class='coverInfo'></div>").text(content).prependTo($(this).parent()).fadeIn("fast");
}).mouseout(function() {
$(this).stop().animate({
'backgroundPosition' : "-40px 0"
}, {
duration : 200,
});
$(this).parent().find(".coverInfo").stop().fadeOut("fast");
})
})
});
</div>
编辑:
我搜索了很多并找到了类似的东西,我把它们和下面给出的答案一起解决了我的问题,这里是代码:
$(function() {
$(".coverImg").css({
'backgroundPosition' : "-40px 0"
}).mouseenter(function() {
var box = $(this).parents(".workshop_img").find(".coverInfo");
var content = $(this).attr("title");
var info = box.text(content);
$(this).stop().animate({
'backgroundPosition' : " -20px -60px "
},90);
info.show();
}).mouseleave(function() {
var box = $(this).parents(".workshop_img").find(".coverInfo");
var content = $(this).attr("title");
var info = box.text(content);
$(this).stop().animate({
'backgroundPosition' : "-40px 0"
},200);
info.stop().hide();
});
});
它刚刚干净,但不能正常工作。 有什么问题?
最佳答案
新框立即显示,因为它最初没有标记为隐藏。 .fadeIn()
仅淡入最初未显示的内容。
你可以像这样让它一开始不可见:
$("<div class='coverInfo'></div>").text(content).hide().prependTo($(this).parent()).fadeIn("fast");
您还可以摆脱正在使用的 .each()
迭代器。你不需要它。你可以只使用:
$(".coverImg").css(...).mouseover(...).mouseout(...);
你根本不需要 .each()
。
我还建议您使用 .hover(fn1, fn2)
而不是 .mouseover(fn1)
和 .mouseout(fn2)
.
而且,看起来您正在创建一个新对象并将其插入到每个鼠标悬停事件中,这样多个此类对象就会堆积在页面中。您应该 .remove()
mouseout 函数中的对象,或者您应该重用以前存在的元素(如果它存在于元素中)而不是创建越来越多的元素。
有时,当您使用鼠标悬停事件并且您也在更改页面时,对页面的更改可能会导致元素失去鼠标悬停,然后隐藏对页面的更改,然后一切重新开始.我无法确定您的情况是否会发生这种情况(我需要一个工作示例来试一试),但似乎有可能。
关于javascript - 为什么盒子马上就消失了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9029847/