簡體   English   中英

更改圖像點擊和鼠標懸停

[英]Change Image OnClick & OnMouseover

我對JS完全陌生,但有時在必要時偶爾擺弄它。 我正在編寫一個功能,當單擊滑動圖像或從其下方的選取框中選擇滑動圖像時,該功能會更改頁面上的兩個圖像(畫廊圖像前后)。 我有工作。 問題是,當鼠標懸停在BEFORE圖像上時,我還需要更改AFTER圖像,而我似乎無法正確地將該變量傳遞給函數-這是我所擁有的:

<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縮略圖名稱變量分別傳遞給鼠標懸停函數(swap1)和(swap2)。 這可能只是一個簡單的語法解決方案-但同樣,我對JS不夠了解,無法弄清楚-任何幫助將不勝感激。

老實說,您的代碼有些復雜。 您可以利用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>

您可以定義一個函數來檢索存儲在data屬性中的路徑,並通過交換數據和源值

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中的onmouseoveronmouseout事件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM