简体   繁体   English

使用 JQuery 一次淡出一个 div

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

I have this function that fades out each div apart from the one that has been clicked on.我有这个功能,可以淡出每个 div 除了已点击的那个。 At the moment they all fade out at the same time, but I would like them to fade out one at a time.目前它们都同时淡出,但我希望它们一次淡出一个。

I would also like the divs to fade out in a random order so extra points to anyone who can tell me how!我还希望 div 以随机顺序淡出,以便任何能告诉我方法的人加分!

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

  var selected = this;

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

});

This is logic you can use: link这是您可以使用的逻辑:链接

$(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();
            })
        });
    });
});

DEMO with bonus randomizing array : jsFiddle带有奖金随机化数组的演示jsFiddle

var selected;

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

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

For the randomness, have a look at:对于随机性,看看:

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

Please give me the bonus points.请给我加分。

This is a bit lengthy, but I like it because it uses a recursive function to randomize the delay of the fades:这有点冗长,但我喜欢它,因为它使用递归函数来随机化淡入淡出的延迟:

 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