2013-07-24 25 views
2

我有一段代碼,像這樣:jQuery的「切換」方法表現wierdly

$(".ani-search").toggle(
    function(){ 
     $("#header .logo a").animate({ 
      marginLeft: "-=30px", 
      marginLeft: "-=60px", 
      marginLeft: "-=90px" 
     }); 
    }, 

    function(){ 
     $("#header .logo a").animate({ 
      marginLeft: "-=60px", 
      marginLeft: "-=30px", 
      marginLeft: "0px" 
     }) 
    } 
); 

當我運行相應的HTML頁面,我沒有得到任何有效的切換響應。會發生什麼事情,只要我打開頁面的類「ani搜索」的圖像閃爍一次,並消失了它,我不會切換任何東西?這是爲什麼發生?

同樣這裏是另一個試驗規程」

<p>Hello world</p> 
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> 
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.0.js"><\/script>')</script> 
<script> 
    $("p").toggle(
     function(){ 
      alert("Cliclk 1"); 
     }, 
     function(){ 
      alert("Click 2"); 
     } 
    );  
</script> 

同樣的事情發生在這裏,只要我加載頁面在瀏覽器中,將文本‘Hello World’閃爍一次,我得到消息的警告框。?用 「點擊2」 完蛋了

爲什麼不能我這裏切換

+3

此形式的toggle()在jQuery 1.9中消失了。 – Barmar

+0

多數民衆贊成在bcos' toggle'已經消失在jQ 1.10版本 – krishgopinath

+0

OMG !!!!那我能做什麼,替代語法是什麼? –

回答

3

棄用和已刪除,創建自己的切換功能:

$(".ani-search").on('click', function() { 
    if (!$(this).data('state')) { 
     $("#header .logo a").animate({ 
      marginLeft: "-=30px", 
      marginLeft: "-=60px", 
      marginLeft: "-=90px" 
     }); 
    }else{ 
     $("#header .logo a").animate({ 
      marginLeft: "-=60px", 
      marginLeft: "-=30px", 
      marginLeft: "0px" 
     }); 
    } 
    $(this).data('state', !$(this).data('state')); 
}); 
,添加相同的CSS屬性多次不多次製作動畫

FIDDLE

注意到,只有最後一個被使用。

+0

對不起,我沒有得到最後一行「添加多個CSS行」是什麼? –

+0

如果您在同一個對象中添加marginLeft三次,則不會動畫marginLeft三次 – adeneo

+0

這裏是http://jsfiddle.net/4ykah/7/ – adeneo

1

toggle不見了。您可能想要使用data屬性自行完成此操作:

$("p").on("click", function() { 
    if ($(this).data("click")) { 
     alert("Click 2"); 
     $(this).data("click", false); 
    } else { 
     alert("Cliclk 1"); 
     $(this).data("click", true); 
    } 
});