猿问

将类逐一添加到一组 span 标签中

我得到的 html 结构是这样的:

<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>

我当前的目标是将每 1s 类“完成”(其某种简单的加载栏)添加到一个又一个的跨度,当最后一个跨度“完成”类时,所有内容都会重新启动并一遍又一遍地循环。有人可以帮我如何用普通 JavaScript 编写这个吗?


尚方宝剑之说
浏览 78回答 1
1回答

斯蒂芬大帝

你可以这样做:var blocks = document.getElementsByClassName('block');(function animateProgress(n) {&nbsp; for (var i = 0; i < blocks.length; i++) {&nbsp; &nbsp; blocks[i].classList[i < n ? 'add' : 'remove']('done');&nbsp; }&nbsp; setTimeout(function() {&nbsp; &nbsp; animateProgress((n + 1) % (blocks.length + 1));&nbsp; }, 400);})(0);.block {&nbsp; float: left;&nbsp; background: #eceded;&nbsp; padding: 1em;&nbsp; margin: 1px;}.block.done {&nbsp; background: #7be47b;}<div class="container">&nbsp; <span class="block"></span>&nbsp; <span class="block"></span>&nbsp; <span class="block"></span>&nbsp; <span class="block"></span>&nbsp; <span class="block"></span></div>
随时随地看视频慕课网APP

相关分类

Html5
我要回答