2016-01-15 28 views
3

一直在学习Jquery,并试图编写一点点代码,当你点击一个按钮时做一个动画,当你再次点击时做相反的动作(基本上每次你从右向左移动一个圆圈点击该按钮很简单的动画,只是努力得到它使用jQuery中的if/else语句)Jquery IF ELSE动画

目前做到这一点我在:

$(document).on('click', '#sub', function(){ 
var moved = 0; 
if (moved == 0) { 
    $('.circle').animate({'margin-left': "300px"}); 
    moved = 1; 
} 
else{ 
    moved = 0; 
    $('.circle').animate({'margin-left': "-300px"}); 
} 
});  

所以我试图移动.circle右边300px,它运行的if语句部分罚款,当我改变移动到值1没有任何反应。我应该使用一个while循环,还是应该以不同的方式做些什么?

回答

1

你应该更全局地声明你的moved var。现在,当点击事件被触发时,moved将始终为0,因为它是以这种方式设置的。

(function() { 
    var moved = 0; 

    $(document).on('click', '#sub', function(){ 
     if (moved == 0) { 
      $('.circle').animate({'margin-left': "300px"}); 
      moved = 1; 
     } 
     else{ 
      moved = 0; 
      $('.circle').animate({'margin-left': "-300px"}); 
     } 
    }); 
})(); 

现在它将在点击事件范围之外“保存”moved变量的状态。

编辑,一点点额外的较短版本的代码:

(function() { 
    var moved = 0; 
    $(document).on('click', '#sub', function(){ 
     $('.circle').animate({ 
      'margin-left': (moved ? "-300" : 300) + "px" 
     }, 500, 'swing', function() { 
      moved = !moved; 
      // or 
      moved = (moved ? 0 : 1); 
     }); 
    }); 
})(); 
+0

感谢您的帮助。这个较短的版本相当不错。 '?'如何?参与其中? – factordog

+2

它被称为[三运营商](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) –

+0

好吧,太棒了!那么即时猜测最后的功能只是做一个检查? – factordog

0

尝试类似这样的事情。当您第一次点击并在第二次点击时将其删除时,向该元素添加类。

$(document).on('click', '#sub', function(){ 

if($('.circle').hasClass("clicked")){ 
    $('.circle').animate({'margin-left': "300px"}); 
    $('.circle').removeClass("clicked"); 
}else{ 
    $('.circle').animate({'margin-left': "-300px"}); 
    $('.circle').addClass("clicked"); 
} 

}); 
1

你设置你的if语句前刚搬到= 0每次...

$(document).on('click', '#sub', function(){ 
    var moved = 0; // <- This line here! 
    if (moved == 0) { 
    $('.circle').animate({'margin-left': "300px"}); 
    moved = 1; 
    } 
    else{ 
     moved = 0; 
     $('.circle').animate({'margin-left': "-300px"}); 
    } 
}); 

你需要移动的功能外的声明,以便它不会重置每次它。

+0

太棒了。没有意识到,通过点击内部的变量,它实际上将值保持为0.感谢您的帮助! – factordog

3

根据需要支持的浏览器,它可能会更好,以动画的手的CSS。 单击圆形并使用css转换时,可以轻松切换类。

事情是这样的: JS

$('.circle').on('click', function() { 
    $(this).toggleClass('clicked'); 
} 

CSS

.circle { transition: margin-left 0.2s; margin-left: -300px; } 
.circle.clicked { margin-left: 3OOpx; } 
+0

是的,这样做最好是更好。只有在这种情况下使用if/else的原因是要了解它是如何工作的以及如何设置它。否则通常一个添加/删除或切换类将是理想的! – factordog