繁体   English   中英

使用 JQuery 一次淡出一个 div

[英]Fade out divs one at a time using JQuery

我有这个功能,可以淡出每个 div 除了已点击的那个。 目前它们都同时淡出,但我希望它们一次淡出一个。

我还希望 div 以随机顺序淡出,以便任何能告诉我方法的人加分!

$(".grid-item").click(function () {

  var selected = this;

  $('.grid > div').not(selected).each(function(i) {
    $(this).fadeTo(200, 0, function(){
      $(this).css("visibility", "hidden");
    });
  });

});

这是您可以使用的逻辑:链接

$(document).ready(function () {
    $(".grid-item").click(function () {
        var selected = this;
        var queue = $.Deferred().resolve(); // create an empty queue
        $('.grid > div').not(selected).get().forEach(function (div) {
            queue = queue.then(function () {
                return $(div).fadeTo(200, 0).promise();
            })
        });
    });
});

带有奖金随机化数组的演示jsFiddle

var selected;

var fader = function() {
    $('.grid > div').not(selected).not(':hidden').first().fadeOut(200, fader);
};

$(".grid-item").click(function () {
    selected = this;
    fader();
});

对于随机性,看看:

http://blog.mastykarz.nl/jquery-random-filter/

请给我加分。

这有点冗长,但我喜欢它,因为它使用递归函数来随机化淡入淡出的延迟:

 var doms = []; var randos = []; var index = 0; $(".grid-item").click(function () { var selected = $(this); doms = $('.grid > div').not(selected); var num = Math.floor(Math.random() * doms.length); for (var i = 0; i < doms.length; i++) { while (randos.indexOf(num) > -1) { num = Math.floor(Math.random() * doms.length); } randos.push(num); } fadeout(); }) window.fadeout = function () { if (doms.length > 0) { var random = $(doms.get(randos[index])); $(random).delay(200 * index).fadeTo(200, 0, function () { $(random).css("visibility", "hidden"); }); doms = doms.not(random); index++; fadeout(); } }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="grid"> <div class="grid-item">hello</div> <div class="grid-item">how</div> <div class="grid-item">are</div> <div class="grid-item">you</div> <div class="grid-item">today</div> </div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM