javascript - mouseenter/leave img to fadeIn/Out text div 不工作

标签 javascript html css

我有一张图片,我想在标题 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
});

Demo

关于javascript - mouseenter/leave img to fadeIn/Out text div 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19277627/

相关文章:

javascript - 将多个对象值显示为表单 Reactjs 中的输入值

html - 为什么我的图像被截断了? Css 面包屑导航栏

html - Bootstrap 日期时间选择器 z-index

html - 将图像粘贴在页面右侧

PHP 从字符串中提取 css 值

javascript - Opera mini css3 变换、渐变、过渡 polyfill?

javascript - showModalDialog() 在 IE11 浏览器中无法正常工作

javascript - 正则表达式 - 获取引号之间的字符

javascript - 是否可以创建一个在 Javascript 中调用时表现得像函数的对象?

css - 显示跨度中间的文本