javascript - 简单的动画播放/倒退按钮

标签 javascript jquery animation

尝试使用 animate.js 框架在播放和反向播放之间切换播放动画。

HTML

<button class="btn">PLAY</button>
<div class="square"></div>

JS

/** animation */
let animeSquare = anime({
  targets: '.square',
  translateX: '100px',
  duration: 500,
  autoplay: false,
});


/** button */
$('.btn').click(function() {
  if ($(this).hasClass('is-active')) {
    animeSquare.reverse();
    $(this).removeClass('is-active');
  } else {
    animeSquare.play();
    $(this).addClass('is-active');
  }
});

问题是我必须按两次按钮才能播放动画。为什么?

代码笔:https://codepen.io/aitormendez/pen/ymyzoq

最佳答案

动漫插件有:

此外,因为您没有循环,所以每次都需要重新启动。

因此,您的代码可以简化为:

let animeSquare = anime({
    targets: '.square',

    direction: 'normal',  // normal or reverse????

    /** Properties to animate */
    translateX: '100px',

    /** Animation settings */
    duration: 500,
    autoplay: false,

    begin: function (anim) {

    },
    complete: function (anim) {
        // change direction..... so the next time you play....
        anim.direction = (anim.direction == 'normal') ? 'reverse' : 'normal';
    }
});

$('.btn').click(function () {
    animeSquare.restart();
});
.square {
    width: 100px;
    height: 100px;
    background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.2.0/anime.min.js"></script>


<button class="btn">PLAY</button>
<div class="square"></div>

关于javascript - 简单的动画播放/倒退按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57110258/

相关文章:

javascript - 如何手动触发字段:error event in ParselyJS

jquery - CSS 或 jQuery 滑动边框底部

html - 如何隐藏完整的悬停动画

javascript - 缓动函数对象运行得太快

java - Swing 动画问题?

javascript - 在悬停主图像上,宽度不适用于缩放图像,请引用下面的附图

javascript - 根据第一行对齐方式设置表头对齐方式

javascript - 我怎样才能使这个动态输入字段下拉而不进入其他字段的中间

javascript - jQuery/AJAX - 单击按钮时将内容加载到 div 中?

javascript - 单击按钮时调用函数