【问题标题】:How to make jQuery animate work only once?如何让 jQuery 动画只工作一次?
【发布时间】:2018-02-17 12:45:58
【问题描述】:

我尝试制作一个动画,如果用户单击下一步并到达隐藏的图像,则 jQuery 动画将生效以显示下一批图像。例如,如果我有六张图像并显示前三张图像,如果用户第四次点击,它现在将滚动查看最后三张图像。现在,我只想使用动画一次。问题是,每次我点击按钮时它仍然会继续动画。如何只使用一次动画?

这是脚本:

next.onclick = function(){
  document.getElementById("defaultPic").src = srcArray[(counter + 1) % numImages];
  counter++;
  if(counter == 5) {
    document.getElementById('next').disabled = true;
    document.getElementById('next').style.opacity = '0.5';
    document.getElementById('prev').disabled = false;
    document.getElementById('prev').style.opacity = '1';
  }
  if(counter == 2) {
    $(function() {
      $('#next').on('click', function () {
        $('#imageList').stop().animate({left : '-=285px'}, 1000);
      });
    });
  }
}

【问题讨论】:

  • 设置一个全局变量作为布尔开关,并使其成为动画的条件检查。第一次运行动画后,翻转布尔开关。

标签: javascript jquery css animation


【解决方案1】:
var animation = true;

next.onclick = function() {

    document.getElementById("defaultPic").src = srcArray[(counter + 1) % numImages];
    counter++;

    if (counter == 5) {
        document.getElementById('next').disabled = true;
        document.getElementById('next').style.opacity = '0.5';
        document.getElementById('prev').disabled = false;
        document.getElementById('prev').style.opacity = '1';
    }

    if (counter == 2) {
        $(function() {
                $('#next').on('click', function() {
                        if (animation) {
                            animation = false;
                            $('#imageList').stop().animate({
                                left: '-=285px'
                            }, 1000, function() {
                                animation = true;
                            }););
                    }
                });
        });
}

我设置了一个名为 animation 的全局布尔值,它设置为 true,然后在点击时检查是否 animation 为 true,如果设置为 false 并播放动画,.animation() 也有一个回调函数,它指定动画何时完成,一旦完成设置 动画 变量恢复为真,如果需要,下次单击可以再次播放动画,如果您不希望它再次播放,只需删除变量和/或整个回调函数。

.animation() docs

【讨论】:

【解决方案2】:

稍微改进您的活动注册:

$(next).one('click', function(){

    document.getElementById("defaultPic").src = srcArray[(counter + 1) % numImages];
    counter++;

    if(counter == 5){
    document.getElementById('next').disabled = true;
    document.getElementById('next').style.opacity = '0.5';
    document.getElementById('prev').disabled = false;
    document.getElementById('prev').style.opacity = '1';
  }

  if(counter == 2){
  $(function () {
    $('#next').on('click', function () {
     $('#imageList').stop().animate({left : '-=285px'}, 1000);
     });
  });
 }

})

【讨论】:

    猜你喜欢
    • 2016-11-10
    • 2015-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    • 2021-09-03
    • 2021-04-21
    相关资源
    最近更新 更多