尝试按百分比增加进度条

时间:2019-04-23 19:35:17

标签: javascript jquery html css algorithm

我正在制作类似于jackbox.tv的琐事游戏,并且我试图弄清楚我需要的逻辑,以便当玩家正确回答问题时按百分比递增进度条(我想说+10每个正确回答的问题的百分比)。我发布了一些示例逻辑,但我认为这不是功能,也不是编写它的最佳方法。

<script>
  $(document).ready(function () {
    users= [{}];

    // This is the example logic for the animation:

    for(let i = 0; i < users.length; i++) {
      let wid = (users[i].score)*1%
      $('.player1').animate({ width: wid }, 2000)
    }

    $('.player1').animate({ width: '90%' }, 2000);
    $('.player2').animate({ width: '75%' }, 2000);
    $('.player3').animate({ width: '50%' }, 2000);
    $('.player4').animate({ width: '70%' }, 2000);
    $('.player5').animate({ width: '45%' }, 2000);
  });
</script>

3 个答案:

答案 0 :(得分:0)

如果您还没有解决方案,它可以为您提供帮助。 https://kimmobrunfeldt.github.io/progressbar.js/是一个非常适合我的图书馆。

enter image description here

答案 1 :(得分:0)

您是否正在搜索类似的内容?

enter image description here

$(document).ready(function () {
  
  var players = [
    {
      "id": 1,
      "score": 0.2
    },
    {
      "id": 2,
      "score": 0.5
    }
  ];
  
  for(var index in players){
    var id = players[index].id;
    var score = players[index].score;
    
    console.log(id);
    var selector = ".bar.player" + id;
    var bar = $(selector);
    bar.css("width", 100 * score + "px");
    
  }
}); 
.container {
  display: block;
  margin-top: 40px;
  clear: both;
  
  height: 20px;
  width: 100px;
  background-color: white;
  border: 1px black solid;
}

.bar {
  height: 18px;
  width: 10px;
  background-color: green;
  margin-top: 1px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="container">
  <div class="bar player1">&nbsp;<div>
<div>

<div class="container">
  <div class="bar player2">&nbsp;<div>
<div>

答案 2 :(得分:0)

我认为这就是您想要做的。主要问题是*1%毫无意义。百分号是modulo / remainder运算符,因此解释器将在您未提供的%之后寻找另一个整数。这只是破损的代码。

相反,您只能执行+ '%'。在播放器2的情况下,添加数字(score变量)和字符串会产生类似"40%"的字符串。CSS属性可以使用字符串分配。

var users = [
  {score: 10},
  {score: 25},
  {score: 40},
  {score: 65},
  {score: 80}
];

$(document).ready(function () {

  for(let i = 0; i < 5; i++) {
    let wid = (users[i].score) + '%';
    $('.player' + (i + 1)).animate({ width: wid }, 2000)
  }

});
.parent {
  width:200px;
}
.player {
  background:red;
  margin-bottom:10px;
  height:20px;
  width:0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="parent">
  <div class="player player1"></div>
  <div class="player player2"></div>
  <div class="player player3"></div>
  <div class="player player4"></div>
  <div class="player player5"></div>
</div>