更改图像OnClick&的onmouseover

时间:2014-01-07 16:57:28

标签: javascript jquery html image

我是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)&amp; (swap2)分别。这可能只是一个简单的语法解决方案 - 但我再也不清楚JS是否足以弄清楚 - 任何帮助都会受到赞赏。

1 个答案:

答案 0 :(得分: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>

您可以定义一个函数来检索存储在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个事件。

相关问题