2014-01-07 76 views
0

我是JS的完整版本,但偶爾會在必要時撥弄它。我正在編寫一個功能,可在頁面下方的選取框中單擊/選擇滑動圖像時,在頁面(在圖庫圖像後的&之前)更改兩個圖像。我有這個工作。問題是,我還需要改變之後的圖像時,之前的圖片位於鼠標過來,我不似乎能夠給變量傳遞給正確的功能 - 這裏是我有:更改圖片OnClick&OnMouseover

<script> 
    function changeImage(imgName) 
    { 
var img = imgName; 
img += 'a.jpg'; 
var img1 = imgName; 
img1 += 'b.jpg'; 

image = document.getElementById('imgDisp'); 
image.src = img;  

image = document.getElementById('imgDisp1'); 
image.src = img1; 
    } 


    function swap1(image) 
    { 
var img = 'newgallery/'; 
img += image; 
img += 'b.jpg'; 
    image = document.getElementById('imgDisp'); 
    image.src = img;  

    } 


    function swap2(image) 
    { 
var img = 'newgallery/'; 
img += image; 
img += 'a.jpg'; 
    image = document.getElementById('imgDisp'); 
    image.src = img;  
    } 
</script> 



<table border=0 width=85%> 
<tr> 
<td align=center valign=top> 
<img id="imgDisp1" src=newgallery/1b.jpg height=80 
onmouseover="swap1(img)" 
onmouseout="swap2(img)" 
> 
<p class=content>BEFORE</b></p></td> 
<td width=35></td> 
<td align=center><img id="imgDisp" src=newgallery/1a.jpg width=550></td> 
</tr> 
</table> 


<marquee behavior="scroll" direction="left" scrollamount="3"  onMouseOver="this.stop();" onMouseOut="this.start();"> 


<?php 

$imagenum = '1'; 
$imageset = 'a.jpg'; 
$imagesetalt = 'b.jpg'; 

while($imagenum < 37){ 

$imagename = "$imagenum$imageset"; 
$imagethumb = "$imagenum$imagesetalt"; 

if($imagenum == '13'){ 

}else{ 

echo"    
<img src=\"newgallery/$imagename\" height=\"120\" border=0 onclick=\"changeImage('newgallery/$imagenum')\"> 
<img src=images/spacer.gif width=25 height=1>"; 

} 

$imagenum++; 

} 


?> 

我可以在調用changeImage函數的選取框中單擊更改圖像,因爲我可以將分配的圖像名稱變量傳遞給該函數。我似乎無法弄清楚如何分別將BEFORE縮略圖名稱變量傳遞給mouseover函數(swap1)&(swap2)。這可能只是一個簡單的語法解決方案 - 但我不知道JS足夠好以解決它 - 任何援助將不勝感激。

回答

1

老實說,你的代碼有點過於複雜。您可以利用HTML元素的data屬性來簡化此操作。

比方說你有限定的容器爲

<div id = 'img_container' class = 'some_class'> 
    <img id = 'image' class = 'some_image_class' src = '/path/to/default/image.jpg' 
    data-alt = '/path/to/hover/image.jpg' /> 
</div> 

您可以定義一個函數來檢索存儲在數據屬性的路徑,並通過

function swap(image){ 
    //temporary variable to hold the alternate image path 
    var newImage = image.data("alt"); 

    //store the image src attribute in the `data-alt` attribute 
    image.data("alt", image.attr("src"); 

    //replace the image src attribute with the new image path 
    image.attr("src", newImage); 

} 

交換數據和源值現在,您可以將事件應用於圖像

$("#image").on("mouseover", function(e){ 
       swap($(e.currentTarget)); 
       }) 
       .on("mouseout", function(e){ 
       swap($(e.currentTarget)); 
       }); 

這將允許您替換第在您的HTML中使用e onmouseoveronmouseout事件。

+0

謝謝你傑森的響應 - 我沒有嘗試它,因爲我已經拼湊出不同的解決方案: SOLUTION我用:http://pastebin.com/rmGxiwPr 注:STACK政策不會讓我的答案我自己的問題,直到8小時過去了。我試着記住並重新正式結束這個問題。 – tekj42