2011-09-07 58 views
1

所以,我用這個可愛的形象交換研究員:使用jQuery分配正確的類將圖像中的圖像交換庫

jQuery Image Swap Gallery

你可以看到它的演示在行動上我網站瀏覽:http://hannahnelsonteutsch.com/v2/art-piece.php

的問題是,與#main_image IMG

<div id="main_image" class="grid_7"> 
    <img class="wide" src="zImages/arrows-2.jpg" /> 
</div> 

請注意class =「wide」。有兩類需要動態應用到圖像,一旦它們「交換」:「寬」「高」,根據我們是否使用縱向或橫向的圖像。

的好處,我有一種預感,一個卓越的編碼器可以利用的,就是對已經正確的類分配給他們每個圖像的縮略圖:

<img class="tall" src="zImages/arrows-1.jpg" /> 
<img class="wide" src="zImages/arrows-2.jpg" /> 
<img class="wide" src="zImages/arrows-3.jpg" /> 
<img class="tall" src="zImages/arrows-4.jpg" /> 
<img class="tall" src="zImages/arrows-5.jpg" /> 

這裏是jQuery的那正在生成圖像交換:

$(document).ready(function() { 
    // Image swap on hover 
    $("#details img").hover(function(){ 
     $('#main_image img').attr('src',$(this).attr('src').replace()); 
     // This is my failed attempt to assign 
     // the correct class to the #main_img img: 
     $('#main_image img').attr('class',$('#details img').attr('class').replace(this)); 
    }); 
    // Image preload 
    var imgSwap = []; 
    $("#details img").each(function(){ 
     imgUrl = this.src.replace(); 
     imgSwap.push(imgUrl); 
    }); 
    $(imgSwap).preload(); 
}); 
$.fn.preload = function() { 
    this.each(function(){ 
     $('<img/>')[0].src = this; 
    }); 
} 

注意兩件事情:

  1. 原始教程有這行代碼:

    $('#main-img').attr('src',$(this).attr('src').replace('thumb/', '')); 
    

    我已經與此替換:

    $('#main_image img').attr('src',$(this).attr('src').replace()); 
    

    的鍵爲.replace( '拇指/', '') vs .replace()

    我們使用CSS縮小圖像,顯着加快懸停時的圖像加載時間。即圖像已經被加載,因爲我們對拇指和主圖像使用相同的圖像。

  2. 我自己試圖回答這一問題沒有奏效

    $('#main_image img').attr('class',$('#details img').attr('class').replace(this)); 
    

所以,這是我在哪裏。任何人有任何想法來解決這個問題?

非常感謝您的時間。

乾杯, 喬恩

回答

1

你需要這樣的jQuery知道你在上空盤旋,其圖像使用$(this)選擇。您也可以使用mouseenter而不是hover,因爲您只需驗證一次鼠標位置。最後,在你的功能中擺脫了replace(),因爲這沒有做任何事情。通過使用attr並更改src或類,您將自動替換該值。下面是我設置頁面的草稿:http://jsfiddle.net/AjBDg/2/

+0

真棒回答,感謝您抽出寶貴的時間給我的背景下,是很容易理解這樣的代碼。 :) – jon

+0

一注:似乎「console.log($(this).attr('class'));」對於生產和調試來說是不必要的。它是否正確? – jon

+0

是的,你可以刪除它。 'Console.Log'只是顯示了firebug中控制檯選項卡里的內容。你應該研究它,因爲它使得在javascript中進行調試變得更容易。 –