基于Express+EJS实现每1秒随机选卡片置顶层(持续15秒)
实现随机卡片置顶动画(持续15秒)
问题描述
我通过Express服务器使用node-fetch获取卡片数据,在EJS模板中循环将每张卡片渲染到div内。已经通过CSS将所有卡片定位在同一位置形成堆叠效果,现在需要实现:每秒钟随机选择一张卡片置于堆叠顶层,且该效果持续15秒。
现有代码及修改方案
服务器代码(无需修改)
import express from 'express' import fetch from 'node-fetch' async function allCarte(req, res) { const data = await fetch('https://pokeapi-enoki.netlify.app/') const response = await data.json() res.render('home.ejs', { response }) } const app = express() app.get('/', allCarte) app.use(express.static('views')) const listener = app.listen(null, () => { console.log(`Example app listening on port ${listener.address().port}`) })
修改后的EJS模板代码
<html> <head> <link rel="stylesheet" href="styles.css" /> </head> <body> <% for(let i=0; i<response.pokemons.length; i++) { %> <!-- 初始化z-index为循环索引,让卡片有基础堆叠层级 --> <div class="Card" id="<%= response.pokemons[i].id %>" style="z-index: <%= i %>; background-color: <%= response.pokemons[i].background_color %>"> <div class="header"> <p class="name"><%= response.pokemons[i].name %></p> <p class="level">Niv. <%= response.pokemons[i].level %><%= response.pokemons[i].abilities[0].icon %></p> </div> <div class="image"> <img src="<%= response.pokemons[i].image %>" alt="" srcset=""> </div> <% for(var a=0; a<response.pokemons[i].abilities.length; a++) { %> <div> <div class="abilities"> <span class="AbIcon"><%= response.pokemons[i].abilities[a].icon %></span> <span class="AbName"><%= response.pokemons[i].abilities[a].name %></span> <span class="AbLevel"><%= response.pokemons[i].abilities[a].power %></span> <p><%= response.pokemons[i].abilities[a].description %></p> </div> </div> <% } %> </div> <% } %> <!-- 新增动画逻辑脚本 --> <script> // 获取所有卡片元素 const cards = document.querySelectorAll('.Card'); // 计算初始最高z-index,避免重复覆盖 let highestZIndex = Math.max(...Array.from(cards).map(card => parseInt(card.style.zIndex))); // 随机置顶一张卡片的函数 function putRandomCardOnTop() { const randomIdx = Math.floor(Math.random() * cards.length); const targetCard = cards[randomIdx]; // 每次置顶都使用更高的z-index,确保显示在最上层 highestZIndex++; targetCard.style.zIndex = highestZIndex; } // 每秒触发一次随机置顶 const intervalId = setInterval(putRandomCardOnTop, 1000); // 15秒后停止动画 setTimeout(() => { clearInterval(intervalId); }, 15000); </script> </body> </html>
CSS代码(无需修改)
.Card { position: absolute; border: 2px solid yellow; border-radius: 10px; font-size: 8px; margin-top: 10%; margin-bottom: 50px; margin: auto ; height: 360px ; width: 250px; }
核心逻辑说明
- 初始化层级:将卡片的初始
z-index设为循环索引,让卡片默认有堆叠顺序,避免全部重叠在同一层。 - 随机置顶逻辑:通过
Math.random()随机选中一张卡片,将其z-index设为当前最高值+1,确保每次选中的卡片都能显示在最顶层。 - 定时器控制:用
setInterval每秒执行一次随机置顶,再用setTimeout在15秒后清除定时器,停止动画。
内容的提问来源于stack exchange,提问作者Rico971
相关产品推荐
相关产品推荐

