gpt4 book ai didi

javascript - 创建一个基本的 HTML/Javascript 排行榜

转载 作者:行者123 更新时间:2023-11-30 09:28:23 25 4
gpt4 key购买 nike

是否可以轻松实现并使用 Javascript 完成,我不确定但是..

如下面的代码所示,我有 5 个玩家,每个玩家的分数都不同。我正在寻找代码,以便它会根据玩家的分数自动重新列出玩家。理想情况下,如果可能的话,我还想将前 3 行着色为金-银-青铜色。

如能提供帮助或为我指明正确的方向,我们将不胜感激。我不确定应该从哪里开始。

#container {
width: 600px;
height: auto;
}

.row {
position: relative;
display: block;
width: 100%;
height: 40px;
border-bottom: 1px solid #AFAFAF;
}

.name {
position: relative;
display: inline-block;
width: 75%;
line-height: 45px;
}

.score {
position: relative;
display: inline-block;
width: 25%;
}
<div id="container">
<div class="row">
<div class="name">Player1</div><div class="score">430</div>
</div>

<div class="row">
<div class="name">Player2</div><div class="score">580</div>
</div>

<div class="row">
<div class="name">Player3</div><div class="score">310</div>
</div>

<div class="row">
<div class="name">Player4</div><div class="score">640</div>
</div>

<div class="row">
<div class="name">Player5</div><div class="score">495</div>
</div>
</div>

最佳答案

您可以使用 nth-child() 将前 3 行设置为您想要的颜色

/* Gold */
.row:nth-child(1) {background: gold;}
/* Silver */
.row:nth-child(2) {background: #c0c0c0;}
/* Bronze */
.row:nth-child(3) {background: #cd7f32;}

接下来要对元素进行排序,您可以将行放入数组中,然后使用 sort对元素进行排序。

document.addEventListener('DOMContentLoaded', () => {
let elements = []
let container = document.querySelector('#container')
// Add each row to the array
container.querySelectorAll('.row').forEach(el => elements.push(el))
// Clear the container
container.innerHTML = ''
// Sort the array from highest to lowest
elements.sort((a, b) => b.querySelector('.score').textContent - a.querySelector('.score').textContent)
// Put the elements back into the container
elements.forEach(e => container.appendChild(e))
})
#container {
width: 600px;
height: auto;
}

.row {
position: relative;
display: block;
width: 100%;
height: 40px;
border-bottom: 1px solid #AFAFAF;
}

.name {
position: relative;
display: inline-block;
width: 75%;
line-height: 45px;
}

.score {
position: relative;
display: inline-block;
width: 25%;
}

.row:nth-child(1) {
background: gold;
}

.row:nth-child(2) {
background: #c0c0c0;
}

.row:nth-child(3) {
background: #cd7f32;
}
<div id="container">
<div class="row">
<div class="name">Player1</div><div class="score">430</div>
</div>

<div class="row">
<div class="name">Player2</div><div class="score">580</div>
</div>

<div class="row">
<div class="name">Player3</div><div class="score">310</div>
</div>

<div class="row">
<div class="name">Player4</div><div class="score">640</div>
</div>

<div class="row">
<div class="name">Player5</div><div class="score">495</div>
</div>
</div>

关于javascript - 创建一个基本的 HTML/Javascript 排行榜,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47918195/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com