2013-06-24 33 views
2

我想從#navCotainer克隆第一個孩子的按鈕,並將其插入最後一個按鈕後。克隆和insertAfter只有一次

現在的問題是:腳本類插入第一個孩子3次。我必須做些什麼才能讓愛爾蘭成爲對的?而且,我在做什麼錯了?

當然

的鏈接小提琴http://jsfiddle.net/ygjDR/和代碼:

<script src="http://code.jquery.com/jquery-1.9.1.js"></script> 

<span class="moveNav8 left8">left</span> 

<div id="navContainer" style="width: 100%; overflow-y: auto;"> 
    <div class="button">1</div> 
    <div class="button">2</div> 
    <div class="button">3</div> 
    <div class="button">4</div> 
</div> 

<script type="text/javascript"> 
    $(document).on('click','.moveNav8', function() { 
     if($(this).hasClass('left8')) { 
      $('.button').animate({ 
       left: '-=305' 
      }, 1000, function() { 
       $('#navContainer div.button:first-child').addClass("xxxx"); 
       $('#navContainer ').children('div.button:first-child').clone().css("background-color","orange").insertAfter("#navContainer div.button:last-child"); 
      }); 
     } 
    }); 
</script> 

<style type="text/css"> 
.button { 
    position: relative; float: left; 
    width:100px; 
    height:50px; 
    background-color:green; 
    margin-right:10px; 
} 
.moveNav8 { 
    position:absolute; 
    top:100px; 
    left:0px; 
    background-color:red; 
    width:40px; 
    height:40px; 
} 
.moveNav8.right8 { 
    left:100px; 
} 
</style> 
+0

_「劇本那種插入第一個孩子的3倍」 _ - 刀片的種類,還是插入? – nnnnnn

+0

@nnnnnn它呢,請看看小提琴,然後點擊左邊 – caramba

回答

2

試試這個:

http://jsfiddle.net/gtttG/

您需要添加一個支票$(".button:animated").length === 0

+0

謝謝,你能解釋一下爲什麼嗎?我只點擊一次,是因爲我們爲4個框(按鈕)設置了動畫效果? – caramba

+0

是的,如果將其應用於多個元素,則會爲每個元素調用animate的回調。在這種情況下,每個'.button'類被調用一次。 – dav

+0

非常感謝您的時間和解釋! – caramba

1

爲每個項目調用動畫回調,追加按鈕4次。採用遞延方式的最後一個動畫之後,而不是執行回調只有一次:

$(document).on('click', '.moveNav8', function() { 
    if ($(this).hasClass('left8')) { 
     $('.button').animate({ 
      left: '-=305' 
     }, 1000).promise().done(function() { 
      $('#navContainer div.button:first-child').addClass("xxxx"); 
      $('#navContainer').children('div.button:first-child').clone().css("background-color", "orange").insertAfter("#navContainer div.button:last-child"); 
     }) 
    } 
}); 

http://jsfiddle.net/ygjDR/3/

+0

感謝您的顯示.promise(),不知道這個函數 – caramba