【问题标题】:How to Toggle Animate Element Position如何切换动画元素位置
【发布时间】:2013-01-12 04:08:48
【问题描述】:

我有一个这样的 jQuery:

 $(document).ready(function(){
       $("#title").click(function(){                
             $(this).animate({left:'30px'});                
       });
 });

我的问题是,是否可以在第二次单击时将 jQuery 元素返回到初始位置,并在第三次单击时返回到左:'30px',依此类推...?

【问题讨论】:

    标签: javascript jquery repeat


    【解决方案1】:

    Demo playground

      // /////////  
      // EXAMPLE 1 
      // Toggle variable value (1,0,1,0...) using Modulo (%) operator
    
      var c = 0;
      $("#el").click(function(){
          $(this).animate({left: ++c%2 * 50 });                
      }); 
    

      // /////////
      // EXAMPLE 2
      // Read current position and use Conditional Operator (?:) 
    
      $("#el").click(function(){
          var leftAt0 = this.offsetLeft < 1 ; // Boolean (true if at 0px left)
          $(this).animate({left: leftAt0 ? 50 : 0 });                
      });
    

      // /////////
      // EXAMPLE 3
      // Toggle two values using array.reverse method
    
      var pos = [0, 50];
      $("#el").click(function(){
          $(this).animate({left: pos.reverse()[0] });                
      });
    

    【讨论】:

    • 是的,我没有看到演示。对不起,无论如何我很困惑,你能解释一下这是怎么可能的吗?我想知道如何设置距离。运动的距离与我想要的不符
    • 在我的代码中30 是您想要的距离。您是否像我在演示链接 ($(function(){ /*code here*/ });) 中所做的那样将代码包装到文档就绪函数中?
    • 你有正确的 CSS 来支持动画吗?请注意演示中 roXon 的位置:相对设置?这对于它的工作至关重要......默认情况下,如果设置了左侧值,标题将不会移动。
    • 举个例子,看看jsfiddle.net/JwFsC/4 vs jsfiddle.net/JwFsC/5(在第二个例子中,我已经注释掉了使它工作的CSS)。
    • 大声笑,确定你需要一个职位,你在我的演示中看到了吗?我也设置了一个元素position。否则使用marginLeft 而不是left
    【解决方案2】:
     $("#title").click(function(){
       var $this = $(this)
       $this.animate({left:$this.position().left ? 0 : '30px'});
     });
    

    【讨论】:

      【解决方案3】:

      试试这个

      $("#title").click(function() {
                   $(this).animate({ left: '30px' }, function(e) {
                       $(this).animate({
                           left: '-=30px'
                       });
                   });
               });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-11-07
        • 1970-01-01
        • 1970-01-01
        • 2018-04-22
        • 1970-01-01
        • 2011-12-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多