2013-02-20 107 views
0

我在HTML页面中有4个图像:1.png,2.png,3.png和4.png。当用户将鼠标指针移动到1.png时,2.png应该替换4.png。同样,如果鼠标指针转到2.png,则应将3.png替换为1.png。将鼠标指针移到图像上

这里是我的代码:

<!doctype html> 
<html> 
    <head> 
     <meta charset="UTF-8"> 
     <script type="text/javascript"> 
      function image1_mouseover() 
      { 
       var img2 = document.getElementById('img2'); 
       var img4 = document.getElementById('img4'); 
       img2.setAttribute('src','exercice1/4.png'); 
       img2.setAttribute('id','img4'); 
       img4.setAttribute('src','exercice1/2.png'); 
       img4.setAttribute('id','img2'); 
      } 

      function image2_mouseover() 
      { 
       var img1 = document.getElementById('img1'); 
       var img3 = document.getElementById('img3'); 
       img1.setAttribute('src','exercice1/3.png'); 
       img1.setAttribute('id','img3'); 
       img3.setAttribute('src','exercice1/1.png'); 
       img3.setAttribute('id','img1'); 
      } 

      function image3_click() 
      { 

      } 
     </script> 
     <style type="text/css"> 
      table 
      { 
       margin-left:auto; 
       margin-right:auto; 
      } 
     </style> 
    </head> 
    <body> 
     <table class="centrer"> 
      <tr> 
       <td><img src="exercice1/1.png" alt="Image 1" id="img1" onmouseover="image1_mouseover()"></td> 
       <td><img src="exercice1/2.png" alt="Image 2" id="img2" onmouseover="image2_mouseover()"></td> 
      </tr> 
      <tr> 
       <td><img src="exercice1/3.png" alt="Image 3" id="img3"></td> 
       <td><img src="exercice1/4.png" alt="Image 4" id="img4"></td> 
      </tr> 
     </table> 
    </body> 
</html> 

它工作在第一,当我把鼠标移动到1.png和2.png取代4.png。但是当我将鼠标移动到2.png时,1.png不会替换3.png,而是我必须将鼠标移动到4.png才能发生。

怎么了?

回答

1

我认为你对图像发生的事情感到困惑。

而不是切换它们的属性,如何切换图像的位置?

function switch_images(i1,i2) { 
    var e1 = document.getElementById('img'+i1), 
     e2 = document.getElementById('img'+i2), 
     e1parent = e1.parentNode; 
    e2.parentNode.appendChild(e1); 
    e1parent.appendChild(e2); 
} 

然后用这个HTML:

<table class="centrer"> 
    <tr> 
     <td><img src="exercice1/1.png" alt="Image 1" id="img1" onmouseover="switch_images(2,4)"></td> 
     <td><img src="exercice1/2.png" alt="Image 2" id="img2" onmouseover="switch_images(1,3)"></td> 
    </tr> 
    <tr> 
     <td><img src="exercice1/3.png" alt="Image 3" id="img3"></td> 
     <td><img src="exercice1/4.png" alt="Image 4" id="img4"></td> 
    </tr> 
</table> 
+0

非常感谢:) – 2013-02-20 20:48:26