mouseenter / leave img to fadeIn / out text div not working

时间:2013-10-09 16:30:00

标签: javascript html css

我有一张图片,我想在标题div中淡出。当鼠标离开时,标题div应该直接在图像上淡入,当鼠标离开时,fadeOut应该淡出。

其次,我想添加一个click toggleClass函数来选择和取消选择图像。选择图像后,标题应保持显示/显示。通过单击取消选择图像时,标题应为fadeOut。

底线:1)mouseenter / leave to fadeIn / out标题2)单击以切换选择类以保持显示标题或取消选择以隐藏。

The 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();
 });

2 个答案:

答案 0 :(得分:0)

您的HTML格式不正确,请尝试使用淡入淡出效果

<div class="image">
<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>

的Javascript

$('.image').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();
 });

http://jsfiddle.net/ZDWzm/1/

答案 1 :(得分:0)

首先在你的小提琴中添加jquery。其次你可以用css本身来实现悬停效果你不需要jquery,除了第二件事。添加一个包装器来包装你的img和overlay,只需添加一些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
});

<强> Demo