2011-08-11 39 views
1

我從頭開始創建下一個/ prev導航,並希望單擊「下一步」按鈕以增加(動畫)每次單擊時由X留下的空白,直到到達結尾(在這種情況-320px),類似的方法爲後退按鈕。我可能是超級密集的 - 但我的javascript低於:在每次點擊時j按j增加

function myFunction() { 

    "use strict"; 

    if (jQuery) { 
     var $next = $(".next"), 
      $back = $(".back"), 
      $box = $(".box"), 
      regWidth = $box.width(), 
      $contain = $(".contain"), 
      len = 0, 
      combinedWidth = 0, 
      len = $box.length; 

     while (len--) { 

      combinedWidth = combinedWidth + $($box[len]).width(); 

     } 


     $contain.width(combinedWidth); 


     $next.bind('click', function (e) { 

      e.preventDefault(); 


      var $this = $(this), 
       $tWidth = $this.width(); 



      $contain.animate({ 

       marginLeft: "+=" + (-regWidth) + "px" 

      }); 

     }); 

     //click event for back 
     $back.click(function (e) { 
      e.preventDefault(); 

      var $this = $(this), 
       $tWidth = $this.width(); 
      $contain.animate({ 

       marginLeft: "+=" + (regWidth) + "px" 

      }); 


     }); 





    } 
}; 

$(function() { 

    myFunction(); 
}); 

的CSS如下:

#wrap { 
    width:320px; 
    margin:0 auto; 
    overflow:hidden; 

} 
.contain { 

    float:left; 
    background:#e9e9e9; 
    height:480px; 

} 

.box 
{ 
    min-height:75px; 
} 

任何幫助將不勝感激!

+0

用Rikudo指出的正確語法更新了代碼!非常感謝! –

回答

8

你使用這樣的:

$element.animate({marginLeft: "+=Npx"}); 

其中N是像素數。 Example

+0

Mucho gracias,我知道它比我做得更簡單:-) –

+0

@ user889962沒有汗水。確保在得到答案時接受答案是正確的,這將有益於回答者,以及社區和將來尋找相同問題的任何未來程序員。 –

+0

我只是覺得我會提到它,因爲它不一定是明顯的:如果你在'='和數字之間加一個空格,那麼'+ = 5'就可以工作,但'+ = 5'就不會工作「T。 – Nolonar

相關問題