[英]jQuery reversing animation on second click
我有一個div元素,在點擊事件中,一個鏈接滑入。這很好用,除了我現在試圖得到它,以便如果第二次點擊鏈接,動畫將反轉到其原始狀態。
我試圖在鏈接中添加一個類,但是當動畫運行時,它最終會執行相同的動畫但是向后。
$('a.contact').click(function() {
$('#contact').animate({marginLeft:'500px'}, {queue:false, duration:'7000'});
$('#contact').animate({width:'500px'}, {duration:'7000'});
$('a.contact').css()
$('a.contact').animate({marginLeft:'-500px'}, '250');
$('a.contact')addClass('open');
return false;
});
處理這個的最簡單方法是使用jQuery切換。 這允許您通過備用點擊激活兩個功能。
$('a.contact').toggle(
function(){
// odd clicks
},
function(){
// even clicks
});
......還有一個快速的jsFiddle來展示 。
請注意,這使用jQuery的切換事件處理程序 ,而不是同名的動畫效果。
注意#2:根據文檔,在jQuery 1.9中刪除了toggle()。 (也就是說,允許您傳遞通過備用點擊激活的多個功能的方法簽名。)
首先,你錯過了一個。 在addClass行中。 這是正確的版本:$('a.contact')。addClass('open');
無論如何,我會這樣做:
// Bind the click event with the live function
$('a.contact:not(.open)').live('click', function() {
// Animate box as wanted and add a class to indicate that the box is open.
// ... Code to animate goes here ...
$(this).addClass('open');
});
$('a.open').live('click', function() {
// Reverse animation and remove class
// ... Code to reverse animation goes here ...
$(this).removeClass('open');
});
您需要與live函數綁定的原因是,當常規.click()綁定發生時,類“open”不會添加到任何元素。
在這里閱讀有關實時方法的信息: http : //api.jquery.com/live/
$('a.contact').click(function(e) {
e.stopPropagation();
var dir = '';
if ($(this).hasclass('to-left'))
{
dir = 'to-rigth';
$(this).removeClass('to-left');
}
else //ini or has class to rigth
{
dir = 'to-left';
$(this).removeClass('to-rigth');
}
dir = $(this).addclass(dir);
if (dir=='to-left')
{
//you code to left
}
else
{
//you code to rigth
}
return false;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.