css 每秒更改随机选择元素的z索引

xu3bshqb  于 2022-11-19  发布在  其他
关注(0)|答案(1)|浏览(184)

在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++) { %>
            <div class="Card" id="<%= response.pokemons[i].id %>" style="zIndex: 0; 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>
        <% } %>
    </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;
}
lhcgjxsq

lhcgjxsq1#

一种方法是使用setTimeout()来启动一个函数,该函数将收集所有卡片,随机选择一张,并将其zIndex设置为适当的值。在设置下一张卡片之前,您需要确保将zIndex重置回原来的值,以避免粘卡。HTML主体中的类似如下内容应该可以达到这个目的:

<script type="application/javascript">
    const cards = document.querySelectorAll('.Card')
    const startTime = new Date()

    function shuffle () {
        const index = Math.floor(Math.random() * cards.length)
        cards[index].style['zIndex'] = 1
        setTimeout(function() {
            cards[index].style['zIndex'] = 0
            const timeNow = new Date()
            const elapsed = timeNow - startTime
            if (elapsed > 15000) return // We're done.
            shuffle()
        }, 1000)
    }

    setTimeout(shuffle, 1000)
</script>

相关问题