質問

I took a couple JQuery tutorials and researched a thumbnail hover swap image function. Eventually I was able to incorporate this into my clients site and it's working! However, the main image is not returning to the original image when I hover off.

Here's my JQuery:

function myFunction(){
    jQuery('#thumbs img').hover(function(){
        jQuery('#largeImage').attr('src',jQuery(this).attr('src').replace('thumb','large'));
    });
}

jQuery(document).ready(function(){
    jQuery(myFunction);
});

My main image is using id=largeImage

My thumbnails are wrapped in a div with id=thumbs

Here's the page where this is working just fine besides returning to the original image: http://test.pillarsoflifebook.com/tables/tabletops/wood/solid-plank-oak/solid-plank-oak/

I can't seem to figure out how to incorporate .hover's mouseout callback function. I was thinking I'd set the largeimg src to a variable and have it replaced in the mouseout function.

Any advice is greatly appreciated! Thanks!

役に立ちましたか?

解決

Try

function myFunction() {
    var $large = jQuery('#largeImage');

    //store the default image as the data src
    $large.data('src', $large.attr('src'));

    var src = jQuery('#largeImage').attr('src');
    jQuery('#thumbs img').hover(function () {
        $large.attr('src', jQuery(this).attr('src').replace('thumb', 'large'));
    }, function () {
        //on mouse leave put back the original value
        $large.attr('src', $large.data('src'));
    });
}

jQuery(document).ready(function () {
    jQuery(myFunction);
});

Another approach

function myFunction() {
    var $large = jQuery('#largeImage');
    //you can also use a closure variable, if you don't want to change the default image in the same page you can use this one.
    //but if you want to change the default image using a function it won't work, in the first approach along with the src attribute if you change the data src that will work
    var src = $large.attr('src');
    jQuery('#thumbs img').hover(function () {
        $large.attr('src', jQuery(this).attr('src').replace('thumb', 'large'));
    }, function () {
        $large.attr('src', src);
    });
}

jQuery(document).ready(function () {
    jQuery(myFunction);
});
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top