简体   繁体   中英

How do I change the mouseenter function to on click function for this image caption Jquery?

This is a code that I've used before for revealing image captions for images. It works great for devices with a mouse, but I'd like to update the code a bit so that it'll accommodate to users without a mouse. Here is the code.

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

Basically, I want to change the mouseenter/mouseleave function and swap it with a click function that's assigned to a link on the page. I also want this click function to reveal the caption associated to an images and hide the caption upon a second click of the link. I've tried just swapping them out but haven't been able to successfully execute the desired result. I'm a bit new to JS and that was the only thing I could think of to make this piece of code work for my intent. Any suggestions?

Working Demo

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

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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