2013-03-24 74 views
0

我有一個圖像庫我正在嘗試製作到目前爲止效果還不錯。我的問題是,無論我如何嘗試,我都無法讓每個圖像都有自己的標題,當我使用JavaScript將它們交換出來時。現在,在任何人對此問題感到不滿之前,我已經看到了這裏,並發現有些人使用html添加字幕,但是當我交換圖像不會工作時。我想也許創建一個空的div並插入HTML文本使用JavaScript,但我怎麼能得到標題加載匹配適當的圖片?數組是這裏唯一的選擇嗎?這是我的問題頁面。同時交換圖像和標題

My site

我離開了「照片」分區空的,所以圖像可以加載到它。到目前爲止,一切正常只是混淆了字幕。

下面是javascript代碼

$('#gallery img').each(function(i) { 
    var imgFile = $(this).attr('src'); 
    var preloadImage = new Image(); 
    var imgExt = /(\.\w{3,4}$)/; 
    preloadImage.src = imgFile.replace(imgExt,'_h$1'); 

    $(this).hover(
     function() { 
      $(this).attr('src', preloadImage.src); 
     }, 
     function() { 
     var currentSource=$(this).attr('src'); 
      $(this).attr('src', imgFile); 
    }); // end hover 
}); // end each 




$('#gallery a').click(function(evt) { 
evt.preventDefault(); 
var imgPath = $(this).attr('href'); 
var oldImage = $('#photo img'); 
var newImage = $('<img src=" ' + imgPath + ' ">'); 
newImage.hide(); 
$('#photo').prepend(newImage); 
newImage.fadeIn(1000); 
oldImage.fadeOut(1000,function(){ 
$(this).remove(); 
}); 
}); 
$('#gallery a:first').click(); 

而且我的HTML

<div id="main">   <!-- Main Content --> 

<div id="photo"> 
</div> 

<div id="gallery"> 
<a href="images/home1_h.jpg"><img src="images/home1.jpg" alt="home 1"></a> 
<a href="images/home2_h.jpg"><img src="images/home2.jpg" alt="home 2"></a> 
<a href="images/home3_h.jpg"><img src="images/home3.jpg" alt="home 3"></a> 
<a href="images/home4_h.jpg"><img src="images/home4.jpg" alt="home 4"></a> 
<a href="images/home5_h.jpg"><img src="images/home5.jpg" alt="home 5"></a> 
<a href="images/home6_h.jpg"><img src="images/home6.jpg" alt="home 6"></a> 
</div> 

</div> 
+1

我建議你創建一個小提琴讓人們可以更好的幫助你.. – Nelson 2013-03-24 16:40:51

+0

你在說什麼標題? – Adidi 2013-03-24 16:44:34

+0

我沒有在那裏,但我想添加一個標題到相應的圖片在「照片」div加載時,我點擊縮略圖 – 2013-03-24 16:45:20

回答

0

我會做這樣的

$('#gallery img').click(function(evt) { 
    var elem = $(this); 
    var oldImage = $('#photo img'); 
    $('#photo').prepend($('<img src=" ' + elem.attr('src') + ' ">').hide().fadeIn(1000)); 
    oldImage.fadeOut(1000,function(){ 
     $(this).remove(); 
     $("#caption").html(elem.attr('alt')); // set the caption 
    }); 
}); 

$('#gallery img:first').trigger('click'); 

和HTML

<div id="main">   <!-- Main Content --> 

<div id="photo"> 
    <div style="text-align:center" id="caption"></div> 
</div> 

<div id="gallery"> 
    <img src="images/home1_h.jpg" alt="home 1"> 
    <img src="images/home2_h.jpg" alt="home 2"> 
    <img src="images/home3_h.jpg" alt="home 3"> 
    <img src="images/home4_h.jpg" alt="home 4"> 
    <img src="images/home5_h.jpg" alt="home 5"> 
    <img src="images/home6_h.jpg" alt="home 6"> 
</div> 

</div> 

和一點CSS的

#gallery img { 
    opacity: 0.8; 
    cursor: pointer; 
} 
#gallery img:hover { 
    opacity: 1 
} 
+0

不改變標題,以匹配圖像,雖然所以你不能有6個不同的標題 – 2013-03-24 22:00:58

+0

它的確如此。它需要圖像的「alt」屬性中的任何內容,並將其用作圖像標題 – TheBrain 2013-03-29 13:31:46