我有一张图片,我想在标题 div 中淡入淡出。当鼠标进入 div 时,标题 div 应直接淡入图像,而当鼠标离开时,标题 div 应直接淡入图像。
其次,我想添加一个单击 toggleClass 函数来选择和取消选择图像。选择图像后,标题应保持显示/显示。单击取消选择图像时,标题应淡出。
底线:1) 鼠标输入/离开以淡入/淡出标题 2) 单击以切换选择类以保持标题显示或取消选择以隐藏。
FiddleJS:http://jsfiddle.net/jhyqt5/cBsqN/
HTML:
<div class="caption">Into the Night</div>
<img src="https://scontent-a-pao.xx.fbcdn.net/hphotos-frc1/189612_10100244250167513_7332862_n.jpg" class="img-circle">
</div>
CSS:
.img-circle{
border-radius: 50%; height: 140px; width: 140px;
}
.caption{
background-color: black; opacity: .7;
text-align: center; line-height: 120px; color: white;
position: absolute; display: none;
border-radius: 50%; height: 140px; width: 140px;
}
JS:
$('.caption').mouseenter(function(){
var image = $(this).find('img'),
caption = $(this).find('div');
caption.height(image.height());
caption.width(image.width());
caption.fadeIn();
}).mouseleave(function(){
var image = $(this).find('img'),
caption = $(this).find('div');
caption.height(image.height());
caption.width(image.width());
caption.fadeOut();
});
最佳答案
首先在你的 fiddle 中添加jquery
。其次,您可以使用 css 本身实现悬停效果,除了第二件事外,您不需要 jquery。添加一个包装器来包装您的 img 和叠加层,并向其添加一些 css 规则。
CSS:
.wrapper{
position:relative;
}
.caption {
background-color: black;
opacity: .7;
text-align: center;
line-height: 120px;
color: white;
position: absolute;
display: none;
border-radius: 50%;
width:140px;
height:140px;
}
.wrapper:hover .caption{ /*Show it when hovered*/
display: block;
}
.wrapper.active .caption{ /*Show it always when parent has class active*/
display: block;
}
HTML:
<div class="wrapper">
<div class="caption">Into the Night</div>
<img src="https://scontent-a-pao.xx.fbcdn.net/hphotos-frc1/189612_10100244250167513_7332862_n.jpg" class="img-circle">
</div>
JS:
$('.wrapper').on('click', function () {
$(this).toggleClass('active'); //toggle the class to add or remove each click
});
关于javascript - mouseenter/leave img to fadeIn/Out text div 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19277627/