2013-11-04 20 views
2

我試圖在第一次單擊時單獨移動300px圖像的一組動畫,再次單擊時將300px左移回到起始位置。Jquery Animate Image右鍵單擊事件,然後回到第二單擊事件左側

我現在所擁有的不起作用。所以它可能是A)我的語法有問題或者B)我的圖像實際上不是以5px呈現。

編輯:這撥弄即會更新爲正確的代碼

Jsfiddle Demo

<!doctype html> 
<html> 
<head> 
<meta charset="UTF-8"> 
<script src="http://code.jquery.com/jquery-latest.min.js"></script> 
    <style type="text/css"> 
     #wrapper { 
      width: 80em; 
     } 

     .image { 
      width: 10em; 
      height: 10em; 
      display: block; 
      position: relative; 
      left:5px; 
     } 
    </style> 

    <script type="text/javascript"> 
    $(document).ready(function() { 
     $(".image").click(function() { 
      if ($('this').css('left') =='5px') {      
       $(".image").animate({"right": "300px"},3000); 
      else 
       $(".image").animate({"left": "300px"},3000);  
      } 
     });  
    });  
    </script> 
</head> 
<body> 
    <div id="wrapper"> 
     <section id="gallery">   
      <img id="avery" class="image" src='images/OAI.jpg' alt= "On Avery Island Album Art"> 
      <img id="overthesea" class="image" src='images/ITAOTS.jpg' alt="In the Aeroplane Over the Sea album art"> 
      <img id="beauty" class="image" src='images/beauty.jpg' alt="Beauty Demo Album Art"> 
      <img id="everthingIs" class="image" src='images/everythingis.jpg' alt="Eveything Is EP Album Art"> 
     </section> 
    </div> 
</body> 
</html>     

回答

1

試試這個:

$(document).ready(function() { 
    $(".image").click(function() { 
     var th = $(this); 
     if ($(th).css('left') == '5px') { 
      console.log("ret"); 
      $(th).animate({ 
       "left": "300px" 
      }, 3000); 
     } else { 
      console.log("sdffsdsff"); 
      $(th).animate({ 
       "left": "5px" 
      }, 3000); 
     } 
    }); 
}); 

Fiddle here.

+0

哦完美,爲什麼把這個(這個)放在一個var中,而不是像我一樣調用它? – nope

+0

爲安全的一面..你可以繼續不放變量也 – Hiral

1

你必須改變$('this')$(this),元素this始終沒有引號。

問候。

+0

是的,我剛剛也注意到了,謝謝! – nope