简体   繁体   中英

How to make elements inside a <div> tag disappear one at a time

I need to implement a vertical scroller and I decided to do that as a list of child elements nested inside a parent and hide/remove/slideUp those one at a time, causing the effect of the elements below it moving up.

I'm trying to do that using JQuery's .each() for iterating over the nested , removing the current one, waiting a bit, and moving to the next one.

I wrote the code below as an attempt to do that. It waits a few seconds and removes all the elements at once, negating the effect I intended to have.

I searched around and all other answers I found around here are about having a delay before acting over all the elements. I can do that already, but what should I do to make the child disappear one at a time?

 $(document).ready(function() { $("#scroller").find("div").each(function() { console.log(this); $(this).delay(10000).slideUp(); // $(this).slideUp(); }); }); 
 <div class="scroller" id="scroller"> <div id="1">texto 1</div> <div id="2">texto 2</div> <div id="3">texto 3</div> </div> 

Check out this code:

 $(document).ready(function() {

      $("#scroller").find("div").each(function (index) {
        var el = $(this);

        setTimeout(function (){ 
          el.slideUp();
        },1000 * index);
      });

 });

The reason they're disappearing all at once is because the .delay function does not pause your code, it simply schedules the functions to run at an offset time in the future. What your code is doing is scheduling .slideUp() to run at 10000 ms in the future for each div all in one go.

What you can do instead of offset each delay by the amount of time you want between elements disappearing. I've set the default delay to be 5000 ms so you can quickly see its effect.

$(document).ready(function() {
  $("#scroller").find("div").each(function(index) {
    $(this).delay( (1 + index) * 5000 ).slideUp();
  });
});

HTML:

<div class="scroller" id="scroller">
  <div id="1">texto 1</div>
  <div id="2">texto 2</div>
  <div id="3">texto 3</div>
</div>

JSFiddle (hit Run at the top to see it again).

I would suggest using the setTimeout method to time each of the disappearances.

setTimeout(function(){
    $("#1").slideUp();
}, 1000);
// ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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