简体   繁体   English

如何在img上覆盖div,并在鼠标悬停时显示另一个div?

[英]How do you overlay a div over an img, and show another div onmouseover?

I have a list thumbnails that lead to larger counterparts when clicked. 我有一个列表缩略图,单击该缩略图会导致较大的副本。 I'd like to show the image title in a div, at the bottom edge of the thumbnail. 我想在缩略图的底部边缘的div中显示图像标题。 Also, when a mouse is moved over the thumbnail, it shows a 2nd div (containing text) over the entire thing. 同样,当鼠标移到缩略图上时,它会在整个对象上显示一个2格(包含文本)。

Whats the best way of doing that? 最好的方法是什么? If a js library is required, jquery is preferred. 如果需要js库,则首选jquery。

如果您准备好使用jQuery,那么这里是Sam Dunn的精彩文章。

<div>
    <img id="image-1" src="yourimage.png" title="My title" />
    <p id="image-1-title"></p>
</div>


$(document).ready(function(){
    $("img[id^='image-']").each(function(i){
        var id = $(this).attr("id");
        var title = $(this).attr("title");
        $("#"+id+"-title").html(title);
    });
});

That should do for image titles :) 这应该为图像标题做:)

I wrote a small plugin some time ago that allows you to do what you need, and with an animation on hover. 我前段时间写了一个小插件,可以让您做自己需要的事情,并且在悬停时带有动画。 It was originally made to add hover background animations but I guess it should be able to do what you need. 它最初是用来添加悬停背景动画的,但是我想它应该能够满足您的需求。

    /*
     * jQuery Animate Background (v0.2)
     * Copyright (c) 2009 Mario "Kuroir" Ricalde ( http://twitter.com/exolimpo )
     * Usage:
     *  $("h1").animateBg();
     *  Con Campos Opcionales:
     *  $("div").animateBg({time:130,add:"span"});
    */
    (function($){
        $.fn.animateBg = function(opciones){
            $.fn.animateBg.defecto = {
                time : "fast", add : "span"
            };
            var config = $.extend({}, $.fn.animateBg.defecto, opciones);
            this.each(function(){
                var c = config;
                var title = $(this).attr("title");
                $(this).append("<"+ c.add +">" + title + "</"+ c.add +">").hover(function(){
                    $(this).children(c.add).fadeIn(c.time);
                },function(){
                    $(this).children(c.add).fadeOut(c.time);
                });
            });
        }
    })(jQuery);

$(document).ready(function(){
    $("#thumb-list p img").animateBg();
});

<div id="thumb-list">
    <p><img src="lol.jpg" title="My title" /></p>
</div>

Sorry if the code doesn't work.. I couldn't test since I'm not at home. 抱歉,如果代码无法正常工作,因为我不在家,所以无法测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM