在JQuery上制作随机动画而不会随机数计算崩溃

问题描述 投票:2回答:1

我正在尝试在滚动时显示一些图像,我想要动画它们是随机的。

我有这个:

$(window).scroll( function(){
    /* Check the location of each desired element */

    $('.conferencia').each( function(i){

        var bottom_of_object = $(this).offset().top + $(this).outerHeight();
        var bottom_of_window = $(window).scrollTop() + $(window).height();

        /* If the object is completely visible in the window, fade it it */
        if( (bottom_of_window) > bottom_of_object ){

            $(this).animate({opacity:'1'},{duration:1500, queue: false});
            randomAnim($(this).find("img"));

        }

    });

});

我不知道这部分是否正确完成,当窗口底部位于对象底部时,图像不会出现。

现在我有一个函数随机Animal()从动画拉取中选择:

function randomAnim(element){

    switch(Math.floor(Math.random() * 3) + 1) {
    case 1:
        element.css({'transform':'rotateX(360deg)'});
        break;
    case 2:
        element.css({'transform':'rotateZ(360deg)'});
        break;
    case 3:
        element.css({'transform':'rotateY(360deg)'});
        break;
    }
}

使用此代码,动画不会执行,但如果我在每次休息之前发出警报(1);动画是有效的,所以我认为问题是Math.random会计算太多的数字并且会崩溃,但我不确定。

编辑:我添加小提琴https://jsfiddle.net/4qfgz0z9/1/它不是完全相同的行为,但我认为它可以帮助。我意识到,如果你滚动一点并停止动画随机工作与否,但如果你滚动和滚动动画不起作用。另一个问题是动画反复重复,而不是在对象出现时只做一次。

javascript jquery animation random scroll
1个回答
1
投票

我添加了一个锁并且动画现在可以正常工作,因此可能多次设置css可能会清除现有的转换

$(document).ready(function() {
  var animated = []

  $(window).scroll(function() {

    $('div').each(function(i) {
      if (animated[i]) {
        return
      }

      var bottom_of_object = $(this).offset().top + $(this).outerHeight();
      var bottom_of_window = $(window).scrollTop() + $(window).height();

      /* If the object is completely visible in the window, fade it it */
      if ((bottom_of_window) > bottom_of_object) {
        animated[i] = true
        $(this).animate({
          opacity: '1'
        }, {
          duration: 1500,
          queue: false
        });
        randomAnim($(this));
      }

    });

  });
});

https://jsfiddle.net/3v2jcqqg/

© www.soinside.com 2019 - 2024. All rights reserved.