应当在JQuery滑块的第3张幻灯片中运行的动画在第一次运行时效果良好,但第二次和连续时间效果不佳。动画与滑块的下一个按钮绑定在一起。单击下一个按钮将从当前幻灯片中删除“显示”属性,并将“显示”属性添加到下一张幻灯片。我已经尝试了数天来通过研究类似的场景并尝试不同的解决方案来调试它,但是这是不行的。有人可以帮忙吗?

function dog(){
    var dog = document.getElementById('dog_2');
    TweenMax.to(dog, 2, {left:"325px", repeat:2, yoyo:true});
}

function moveRight() {
    $('#slider ul').animate({
        left: - slideWidth
    }, 300, function () {
        $('#slider ul li:first-child').appendTo('#slider ul');
        $('#slider ul').css('left', '');
    });
};

$('#slider').on('click', 'a.control_next', function (){
    moveRight();

    if($("li").next().length > 0){
        var next = $("#slider .slideshow .show").removeClass("show").next("li");
        next.addClass("show");
    }

    else if  {
        $("li:last").removeClass("show");
        $("li:first").addClass("show");
    }

    if ($("li").eq(2).hasClass("show")){
        dog();
    };
});

最佳答案

问题是,每次单击下一个或上一个按钮时,对dog()函数的调用都会在目标div上创建一个新的tweenmax动画实例。多个动画实例使其挂起。

方法1:First jsfiddle 1,维护一个tweenmax动画对象。只需在一定条件下通过调用dog()重新启动它即可;功能。

jQuery(document).ready(function ($) {
  var animate;
  var doggy = document.getElementById('dog_2');
  animate = TweenMax.to(doggy, 2, {left:"325px", repeat:true, yoyo:true});

   function dog(){
     animate.restart();
   }
  ...........
  .............
  });


方法2:Second jsfiddle。通过使用jQuery注入HTML来创建目标DIV。适用于动态场景。

function dog(){
  var dog = document.getElementById('dog_2');
  dog.remove();
  $("li.dog").html("<div id=\"dog_2\"><img src=\"https://pbs.twimg.com/profile_images/604644048/sign051.gif\" style=\"height:50px;width:50px\"/></div>");
  var dog = $('#dog_2');
  //TweenMax.killTweensOf(dog);
  animate =TweenMax.to(dog, 2, {left:"325px", repeat:true, yoyo:true});
  animate.play();
}


$('#slider').on('click', 'a.control_next,a.control_prev', function (){
    if($(this).hasClass('control_next'))
    {moveRight();}
    else{ moveLeft();}
    var prev = $("#slider .slideshow .show").removeClass("show").next("li");
    prev.addClass("show");
    if ($("li").eq(2).hasClass("show")){
      // call dog(); on some condition if required.
    };
    dog();
});

关于javascript - onclick后第二次不执行该功能,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27340559/

10-10 13:17