【问题标题】:jQuery add class to random div after random delayjQuery在随机延迟后将类添加到随机div
【发布时间】:2015-03-24 08:34:04
【问题描述】:

我正在尝试在 0.5 到 5 秒之间的随机时间段后将类“翻转”添加到随机“子”div。然后应该在三秒后删除该类。

div 的布局如下:

<div class="parent">
    <div class="child"><img src="image.jpg"></div>
    <div class="child"><img src="image.jpg"></div>
    <div class="child"><img src="image.jpg"></div>
    <div class="child"><img src="image.jpg"></div>
    <div class="child"><img src="image.jpg"></div>
    <div class="child"><img src="image.jpg"></div>
</div>

到目前为止,我的 jquery 是:

$(document).ready(function () {
    var $children = $(".child");
    var interval = setInterval(function () {
        var $d = $children.not(".flip");
        $d.eq(Math.floor(Math.random() * $d.length)).addClass('flip');
        if ($d.length == 1) {
            clearInterval(interval);
        }
    }, Math.floor((Math.random() * 4500) + 500));
});

不太确定如何在 3 秒后再次删除该类?

谢谢!

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    您需要在间隔中的函数末尾使用setTimeout

    $(document).ready(function () {
        var $children = $(".child");
        var interval = setInterval(function () {
            var $d = $children.not(".flip");
            var $el = $d.eq(Math.floor(Math.random() * $d.length));
            $el.addClass('flip');
            setTimeout(fucntion() { $el.removeClass('flip'); }, 3000 );
            if ($d.length == 1) {
                clearInterval(interval);
            }
        }, Math.floor((Math.random() * 4500) + 500));
    });
    

    【讨论】:

      【解决方案2】:

      从您的代码中,由于您只想添加一次类以及超时计时器,因此您还必须使用另一个额外的类

      $(document).ready(function () {
          var $children = $(".child");
          var interval = setInterval(function () {
              var $d = $children.not(".done");
              var $el = $d.eq(Math.floor(Math.random() * $d.length)).addClass('flip done');
              setTimeout(function () {
                  $el.removeClass('flip');
              }, 3000)
              if ($d.length == 1) {
                  clearInterval(interval);
              }
          }, Math.floor((Math.random() * 4500) + 500));
      });
      

      演示:Fiddle


      另一种选择是

      $(document).ready(function () {
          var $todo = $(".child");
          var interval = setInterval(function () {
              var $el = $todo.eq(Math.floor(Math.random() * $todo.length)).addClass('flip');
              setTimeout(function () {
                  $el.removeClass('flip');
              }, 3000)
              if ($todo.length == 1) {
                  clearInterval(interval);
              }
              $todo =$todo.not($el);
          }, Math.floor((Math.random() * 4500) + 500));
      });
      

      演示:Fiddle

      【讨论】:

        猜你喜欢
        • 2013-05-21
        • 2012-10-26
        • 2016-02-17
        • 1970-01-01
        • 2013-12-23
        • 1970-01-01
        • 2011-11-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多