How to create image captions with 'alt' text using jquery click function

北慕城南 提交于 2019-12-12 02:44:23

问题


I'm creating an image gallery that shows the alt text as captions for each individual image. Right now I have something that uses the mouseenter/mouseleave function for this desired result.

JS

$(function () {
    $(".thumb").mouseenter(function () {
        var $t = $(this);
        var $d = $("<div>");
        $d.addClass("desc").text($t.attr("alt")).css({
            width: $t.width(),
            height: $t.height() - 20,
            top: $t.position().top
        });
        $t.after($d).fadeTo("fast", 0.3);
        $d.mouseleave(function () {
            $(this).fadeOut("fast", 0, function () {
                $(this).remove();
            }).siblings("img.thumb").fadeTo("fast", 1.0);
        });
    });
});

HTML

<div>
    <img class="thumb" src="myImage1" alt="caption">
</div>
<div>
    <img class="thumb" src="myImage2" alt="caption">
</div>

Here's an example of what I had in mind in terms of how the captions will look visually. http://jsfiddle.net/CTQvN/168/

Basically I want to be able to show the captions of multiple images simultaneously by clicking on a link somewhere on the page that looks like a button, instead of the mouseenter functions so that I can accommodate to smartphones an other devices without a mouse. I'd like to maintain the visual aesthetics of this current script while updating the function portion of what I have so far. I'm very new to JavaScript and I realize that my code is not the best right now so please bear with me on this one. I'm very open to suggestions, and I'm extremely willing to learn how to get this to work. Cheers!


回答1:


Here's one possibility:

EXAMPLE

$('.thumb').click(function() {
    $(this).trigger('mouseenter'); 
});

Or if you'd like a button:

EXAMPLE

$('button').click(function() {
    $('.thumb').trigger('mouseenter'); 
});


来源:https://stackoverflow.com/questions/17977696/how-to-create-image-captions-with-alt-text-using-jquery-click-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!