简体   繁体   中英

Swap Image Src JQuery Not Working?

...but for some reason it won't work. Beginner here, so if someone could explain what I'm doing wrong, I'd really appreciate it. xD

http://codepen.io/DylanEspey/pen/xgwJr An example Codepen I threw together really quick to try to illustrate my problem.

I hate that I've had to ask so many questions, but this is my first project where I've kind of had my own leeway, and I've been struggling to get it done before deadlines so I can impress people. xD That and college has made my schedule a mess, so I've been making really dumb mistakes. That, and I just started learning Javascript a few weeks ago...

Try this:

$('.thumbnails img').click(function () {
    var thmb = this;
    var src = this.src;
    $('.project-img img').fadeOut(400, function () {
        thmb.src = this.src;
        $(this).attr('src', src).fadeIn(400);
    });
});

Fiddle Demo

The problem is that the overlay used for your fade effect is preventing you from clicking on the image which is underneath it. The solution is to, instead of listening for a click on the image, listen for it on the overlay, and adjust the references accordingly.

I have forked your codepen to reflect this: http://codepen.io/anon/pen/qlkob

JS:

$(document).ready(function() {
    $('.thumbnails .overlay').click(function() {
        var img = $(this).find('img')[0];
        var thmb = img;
        var src = img.src;
        $('.project-img img').fadeOut(400,function(){
            thmb.src = this.src;
            $(this).attr('src', src).fadeIn(400);
        });
    });
});

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