2014-01-23 121 views
0

我帶了幾個JQuery教程並研究了一個縮略圖懸停交換圖像函數。最終我能夠將其納入我的客戶網站,它的工作!但是,當我懸停時,主圖像沒有返回到原始圖像。JQuery懸停交換圖像 - 未返回原始圖像

這裏是我的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); 
}); 

我的主圖像是以ID = largeImage

我的縮略圖被包裹在id爲一個div =大拇指

在此處,這是工作只是網頁除了返回到原始圖像: http://test.pillarsoflifebook.com/tables/tabletops/wood/solid-plank-oak/solid-plank-oak/

我似乎無法弄清楚如何合併.hover的mouseout回調函數。我想我會將largeimg src設置爲一個變量,並將其替換爲mouseout函數。

任何意見非常感謝!謝謝!

+0

我勸你不要用這種方法。這是舊的和低效率的。請嘗試使用CSS:懸停選擇器,svg資產和CSS3轉換。 – 0xcaff

回答

0

嘗試

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

另一種方法

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); 
}); 
+0

我嘗試了第一種方法,它效果很好!非常感謝!我會一步一步地經歷它,直到我更好地理解它,但現在 - 它是功能性的! – user40823