2013-02-20 104 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