简体   繁体   中英

Adding class to group of span tags one by one

I got html structure like this:


<body>
    <div class="container">
        <span class="block done" id="1"></span>
        <span class="block" id="2"></span>
        <span class="block" id="3"></span>
        <span class="block" id="4"></span>
        <span class="block" id="5"></span>
    </div>
    <script src="loaders.js"></script>
</body>

My current goal is to add every 1s class "done" (its some kind of simple loading bar) to spans one by one and when last span got "done" class everything restart and loop over and over. Can someone help me how to write this in vanilla JavaScript?

You could do it like this:

 var blocks = document.getElementsByClassName('block'); (function animateProgress(n) { for (var i = 0; i < blocks.length; i++) { blocks[i].classList[i < n ? 'add' : 'remove']('done'); } setTimeout(function() { animateProgress((n + 1) % (blocks.length + 1)); }, 400); })(0);
 .block { float: left; background: #eceded; padding: 1em; margin: 1px; } .block.done { background: #7be47b; }
 <div class="container"> <span class="block"></span> <span class="block"></span> <span class="block"></span> <span class="block"></span> <span class="block"></span> </div>

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