2012-08-26 25 views
1

如果我犯了一個愚蠢的錯誤,它遲了一點,所以請原諒。出於某種原因,下面的代碼:在動畫記錄發佈動畫值之前存儲寬度值

$(".myClass").each(function(){ 
    widths[$(this).attr("id")] = $(this).width(); 
    if ($(this).attr("id") != $(clickedExpand).attr("id")) 
    { 
     $(this).animate({ 
      width: '10px' 
     }); 
    } 

}); 

該陣列之前在代碼初始化爲

var widths = new Array(); 

。出於某種原因,儘管我在動畫開始之前記錄了寬度,但我正在獲取數組中的動畫後值。看起來好像動畫完成,然後值被記錄下來。我試圖把它從函數中取出幷包裝在另一個函數中,但是我得到了相同的結果。

任何幫助將不勝感激!

整個代碼:

var slateWidths = {}; 
$(".slateExpand").click(function(){ 
    var clickedExpand = $(this).closest(".slate"); 

    $(".slate").each(function(){ 
     slateWidths[$(this).attr("id")] = $(this).outerWidth(); 
     if ($(this).attr("id") != $(clickedExpand).attr("id")) 
     { 
      $(this).animate({ 
       width: '10px' 
      }); 
      $(this).find($('.slateExpand')).hide(); 
     } 

    }); 

    $(this).text("Restore"); 
    $(this).removeClass("slateExpand").addClass("slateRestore"); 
    $(".slateRestore").on("click",function(){ 

     $(".slate").each(function() 
     { 
      alert(slateWidths[$(this).attr("id")]); 
      //var width = slateWidths[$(this).attr("id")]; 
      $(this).animate({ 
       width: slateWidths[$(this).attr("id")] 
       }); 
     }); 
    }); 
}); 
+2

切勿使用'new Array()',並且在實際需要對象時不要使用數組。 ('var widths = {};') – Ryan

+0

有趣...怎麼回事?此外,這個問題仍然存在:( –

+0

)你什麼時候得到錯誤的值?直接從'width()'方法,或者你設置/讓他們到別的地方?告訴我們整個代碼 – Bergi

回答

1
// first of all save all widths for all .slate 
var slateWidths = {}; 
$(".slate").each(function(){ 
    slateWidths[$(this).attr("id")] = $(this).width(); 
}); 

$(".slateExpand").click(function(){ 
    var $slate = $(this).closest('slate');  

    if($slate.hasClass('hidden')) { 

     $slate.animate({ 
      width: slateWidths[$slate.attr('id')] 
     }); 
     $(this).text("hide"); 
     $slate.removeClass("hidden")   
    }else{ 

     $slate.animate({ 
      width: '10px' 
     }); 
     $(this).text("Restore"); 
     $slate.addClass("hidden") 
    }  
}); 
+0

這是一個很棒的解決方案,但我需要在點擊時保存它,因爲最初的寬度不是恆定的,但可能會根據您對slates做的改變而改變,但是我找到了解決方案,您只需解除綁定()事件。非常需要花時間來解決這個問題,如果你願意,你可以拋出解決方案,並給你的支票:) –

+0

換句話說,即使類改變,點擊綁定仍然適用於div,所以你需要點擊刪除它。 –

+0

正如你所看到的,我不會在任何地方搞亂'slateExpand'類:)無論如何,我很高興你解決了你的問題 – Peter

0

好吧,如果你遇到類似的問題,有一個簡單的解決方案。問題在於,儘管班級發生變化,點擊仍未從div中解除綁定。因此,它首先重新運行記錄寬度的代碼。這會導致動畫不能播放,因爲現在的寬度與當前的寬度相同。要解決這個問題,只需添加

$("theDiv").unbind("click); 

刪除事件處理程序。這將防止上一課的點擊事件發生。