【问题标题】:How do I animate a scale css property using jquery?如何使用 jquery 为缩放 css 属性设置动画?
【发布时间】:2016-05-27 13:51:16
【问题描述】:

我正在尝试使用 jQuery 单击按钮时弹出一个带有“气泡”类的圆形 div。我想让它从无到有并成长为全尺寸,但我无法让它工作。这是我的代码:

HTML 显示气泡 ... CSS

.bubble {
    transform: scale(0);
}

Javascript

 $('button').click(function(){
     $('.bubble').animate({transform: "scale(1)"}, 5000, 'linear');
 });

【问题讨论】:

  • 您想何时缩放项目?在悬停,页面加载或其他什么?请清除您的问题。
  • 您只能使用 jq animate() 方法为数字属性设置动画。最好的办法是切换一个类,处理 CSS 过渡

标签: javascript jquery html css jquery-animate


【解决方案1】:

您可以使用 CSS 执行转换,然后只需使用 Javascript 作为“开关”,它会添加类来启动动画。试试这个:

$('button').click(function() {
  $('.bubble').toggleClass('animate');
})
.bubble {
  transform: scale(0);
  width: 250px;
  height: 250px;
  border-radius: 50%;
  background-color: #C00;
  transition: all 5s;
}

.bubble.animate {
  transform: scale(1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button>Toggle</button>
<div class='col-lg-2 col-md-2 well bubble'></div>

【讨论】:

  • 我知道这是如何工作的,但还没有弄清楚如何控制动画时间和缓动。有什么线索吗?
  • 有几个 CSS 规则可供您使用,请参阅 MDN 了解更多信息,并尝试左侧的链接以了解可用规则。
【解决方案2】:

目前您不能将animatetransform 属性see here 一起使用

但是,您可以添加 css transition 值并修改 css 本身。

var scale = 1;
setInterval(function(){
  scale = scale == 1 ? 2 : 1
  $('.circle').css('transform', 'scale('+scale+')')
}, 1000)
.circle {
  margin: 20px auto;
  background-color: blue;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  transform: scale(1);
  transition: transform 250ms ease-in-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="circle"></div>

【讨论】:

    【解决方案3】:

    最好使用 CSS3 动画。对于频繁间隔的动画,您可以使用浏览器支持前缀(-webkit、-moz 等)-

    @keyframes fullScale{
        from{
            transform:scale(0);
        }
        to{
            transform:scale(1);
        }
    }
    .bubble:hover{
        animation: fullScale 5s;
    }
    

    参考此链接- http://www.w3schools.com/css/css3_animations.asp

    或者@Rory 的上述解决方案也是在附加事件上添加类的好方法。

    【讨论】:

      【解决方案4】:

      使用步骤回调和计数器。这里的计数器只是数字 1。
      'now' 将在 5000 毫秒内从 0 到 1。

      $('.bubble').animate({transform: 1},
      {duration:5000,easing:'linear',
      step: function(now, fx) {
      $(this).css('transform','scale('+now+')')}
      })
      

      Vanilla JS 动画方法(现代浏览器支持,无 IE)

      https://drafts.csswg.org/web-animations-1/#the-animation-interface

      $('.bubble').get(0).animate([{"transform": "scale(1)"}],
      {duration: 5000,easing:'linear'})
      

      【讨论】:

      • 当您使用动态定位和动画到无法用 CSS 设置的东西时,这是最有用的
      【解决方案5】:

      您可以使用 Velocity.js。 http://velocityjs.org/ 例如:

      $("div").velocity({
        "opacity" : 0,
        "scale" : 0.0001
      },1800)
      

      【讨论】:

        猜你喜欢
        • 2011-12-23
        • 1970-01-01
        • 2011-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-20
        • 2021-01-14
        • 2013-09-10
        相关资源
        最近更新 更多