【问题标题】:how to animate marginTop of a div with click如何通过单击为 div 的 marginTop 设置动画
【发布时间】:2013-07-31 16:32:56
【问题描述】:

我想用它的 marign-top 属性为 div 设置动画。最初它设置为 margin-top:10%。点击它会将 margin-top 减少到 5% 并显示下一个 div 及其内容(使用切换( ))。

#login
{
margin:10% auto;
......
}


$("#login").click(function()
{   
  $( "#outer_wrapper" ).toggle( "clip",300);
  $("#login").animate({marginTop:'5%'});
}

这很好。但是当再次点击“#login”时如何回到初始的“margin-top:10%”?

【问题讨论】:

    标签: click jquery-animate toggle margin


    【解决方案1】:

    在 CSS3 中,您可以使用过渡属性制作一些常见的动画。例如

    .test{
       -webkit-transition: all .5s ease;
       -moz-transition: all .5s ease;
    }
    

    然后直接设置元素的margin top样式(就像你使用jquery一样)

    $('.test').css('margin-top','5%');
    

    然后它会自动应用动画。这种“线性”动画可以对大多数 CSS 更改生效,例如宽度、高度、背景颜色等。

    【讨论】:

      【解决方案2】:

      如果你只使用 jQuery:

      $("#login").click(function() {   
        if($('#login').css('margin') == '10%'){       // check if has 10% margin atm.
          $( "#outer_wrapper" ).toggle( "clip",300);  // if true => apply the 5% margin
          $("#login").animate({marginTop:'5%'});
        } else {
          // whatever you also want to do here...
          $("#login").animate({marginTop:'10%'});     // otherwise apply the 10%
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2013-03-18
        • 1970-01-01
        • 2013-01-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-10
        • 2020-02-26
        相关资源
        最近更新 更多