Javascript 如何将文本悬停在div img上?

Javascript 如何将文本悬停在div img上?,javascript,jquery,css,Javascript,Jquery,Css,我想知道如何在img上的div中显示文本?我不想使用背景图像,因为我的div命名相同,最终会循环,所以我想让它保持打开状态,以便回显数据库中的文本 那么,有没有一种方法可以根据.box创建一个带有文本的唯一悬停.box重复多次。我可以通过CSS或jQuery来完成吗 让我知道这是否有意义,或者您需要更多信息 谢谢, 凯蒂你可以使用一个绝对定位的div,它是div的子div,其中包含图像。 例如: 希望这有帮助 编辑:哎呀!误读了这个问题。 要实现悬停,只需添加display:none;要#chi

我想知道如何在
img
上的
div
中显示文本?我不想使用背景图像,因为我的div命名相同,最终会循环,所以我想让它保持打开状态,以便回显数据库中的文本

那么,有没有一种方法可以根据
.box
创建一个带有文本的唯一悬停
.box
重复多次。我可以通过CSS或jQuery来完成吗

让我知道这是否有意义,或者您需要更多信息

谢谢,
凯蒂

你可以使用一个绝对定位的div,它是div的子div,其中包含图像。 例如:

希望这有帮助

编辑:哎呀!误读了这个问题。 要实现悬停,只需添加display:none;要#child并使用此jQuery在悬停时显示它,请执行以下操作:

$(function(){
    $('.parent').mouseenter(function(){
        $(this).children('.child').fadeIn();
    }).mouseleave(function(){
        $(this).children('.child').fadeOut();
    });
});
编辑#2:将所有内容都更改为类,这样您就可以拥有任意数量的类

编辑#3:这正在成为一种习惯:)修复了一些拼写和css

编辑#4:根据kokos的评论,悬停可以在纯css中完成(但没有jquery的时尚性)

请参见以下正确的(纯css)实现:

这是密码

HTML:


如果希望页面上的任何图像都有标题,我建议使用jquery检查哪些图像需要标题,然后显示或隐藏标题

$(".imgCon>img").each(function() {
    $(this).hover(

    function() {
        $(this).parent().find("span").toggleClass("captionShow");
    });
});
这将检查图像容器中的每个图像,然后在图像悬停时显示标题

假设您的html的结构如下:

<div class="imgCon">
    <img width="100" height="100" src="#" alt="Image"/>
    <span class="captionHide">Some caption text</span>
</div>
<div class="imgCon">
    <img width="100" height="100" src="#" alt="Image"/>
    <span class="captionHide">Some caption text</span>
</div>

您可能只需要
title
属性。在div或image上设置它,当您用鼠标悬停时,浏览器将自动显示它。如果您需要/想要对文本显示格式进行更多控制,MrBorna的解决方案会更好。有关“DOM标题属性”或“工具提示”的描述,请搜索,例如:

函数如何。悬停(在上方,向外)'?我想它也是这样。你也可以用css做悬停:
.parent:hover.child{display:block;}
。两者都正确,不过我更喜欢使用mouseleave和mouseenter,因为代码中更清楚每个处理程序是什么以及它是什么doing@jammypeach-请记住,
hover
的工作原理与
mouseenter/leave
略有不同。感谢您的回复!我只是通过CSS做的。我一直在使用CSS3转换,所以逐渐消失的幻想将通过我将使用的悬停。在我的网站上线之前,我必须回去为不理解CSS3的浏览器编写修复程序。
<div class="container">
  <img src="http://colorvisiontesting.com/plate%20with%205.jpg"/>
  <div class="child"><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua</p></div>
</div>
.child{
    position: absolute;
    height: 80px;
    background-color: rgba(0,0,0,0.7);
    left:0; bottom: 0;
    color:white;padding:10px;
    display:none;
}

.container{
    position:relative;
    display:inline-block;
}
.container:hover .child{display:block;}
$(".imgCon>img").each(function() {
    $(this).hover(

    function() {
        $(this).parent().find("span").toggleClass("captionShow");
    });
});
<div class="imgCon">
    <img width="100" height="100" src="#" alt="Image"/>
    <span class="captionHide">Some caption text</span>
</div>
<div class="imgCon">
    <img width="100" height="100" src="#" alt="Image"/>
    <span class="captionHide">Some caption text</span>
</div>
.captionHide
{
    display:block;
    visibility:hidden;
}
.captionShow
{
    display:block;
    visibility:visible;
}