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

Ste*_*eyG 4 html javascript css jquery leaderboard

是否可以轻松实现并使用 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%;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

Get*_*awn 7

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

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

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

/* Gold */
.row:nth-child(1) {background: gold;}
/* Silver */
.row:nth-child(2) {background: #c0c0c0;}
/* Bronze */
.row:nth-child(3) {background: #cd7f32;}
Run Code Online (Sandbox Code Playgroud)
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))
})
Run Code Online (Sandbox Code Playgroud)
#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;
}
Run Code Online (Sandbox Code Playgroud)

  • 有一些 css 出于某种原因要求 div 位于同一行(没有研究它)。但我修好了。 (2认同)