使用JavaScript中的评级栏可视化评级

时间:2017-12-27 18:56:05

标签: javascript jquery html css

我有一些从0到1的评级,并希望获得五个评级栏。评级栏应代表评级。

以下是我想要实现的一些例子

enter image description here

enter image description here

在这些栏下方,我想显示完整容器的平均值和数量。

所以我去找这个代码



var ratings = [0.8, 0.9, 0.1, 0.1, 0.9, 0.1, 0.6, 1, 0.1, 0.4, 0.6, 0.8, 0.9, 0.6, 0.1, 1, 1];

$(document).ready(function() {
  initializeStatistics();
});

function initializeStatistics() {
  var ratingBarsLength = $(".ratingBar").length;

  var ratingBars = {};

  for (var i = 1; i <= ratingBarsLength; i++) {
    ratingBars[i] = [];
  }

  splitRatings(ratingBars, ratingBarsLength);
  setRatingBars(ratingBars, ratingBarsLength);
  createFinalRatingBar(ratingBarsLength);
}

function splitRatings(ratingBars, ratingBarsCount) {
  ratings.forEach(function(rating) {
    var containerIndex = Math.round(ratingBarsCount * rating);
    ratingBars[containerIndex].push(rating);
  });
}

function setRatingBars(ratingBars, ratingBarsCount) {
  for (var i = 1; i <= ratingBarsCount; i++) {
    var currentBar = $("#ratingBar" + i);
    var barWidth = (ratingBars[i].length / ratings.length) * 100;
    currentBar.width(barWidth + "%");
  }
}

function createFinalRatingBar(ratingBarsLength) {
  var totalRatings = 0;

  for (var i = 0; i < ratings.length; i++) {
    totalRatings += ratings[i];
  }

  var imageCounter = 0;

  for (var j = 0; j < ratingBarsLength; j++) {
    var imageIsFull = j < (totalRatings / ratingBarsLength);
    if (imageIsFull) {
      imageCounter++;
    }
  }

  $("#finalRatingContainer").html("average: " + (totalRatings / ratingBarsLength) + " | containers: " + imageCounter + " full containers");
}
&#13;
.ratingBar {
  margin-top: 20px;
  height: 30px;
}

#ratingBar1 {
  background-color: #ff6f31;
}

#ratingBar2 {
  background-color: #ff9f02;
}

#ratingBar3 {
  background-color: #ffcf02;
}

#ratingBar4 {
  background-color: #88b131;
}

#ratingBar5 {
  background-color: #99cc00;
}

#finalRatingContainer {
  margin-top: 20px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="ratingBar5" class="ratingBar"></div>
<div id="ratingBar4" class="ratingBar"></div>
<div id="ratingBar3" class="ratingBar"></div>
<div id="ratingBar2" class="ratingBar"></div>
<div id="ratingBar1" class="ratingBar"></div>

<div id="finalRatingContainer"></div>
&#13;
&#13;
&#13;

如您所见,计算结果不正确。第一个条和第二个条的宽度大于第四个和第五个条的宽度。但平均值接近零而不是五。

我的计算错了吗?我的酒吧错了吗?

在查看条形图时,最终评级应该具有类似

的输出
  

平均值:超过2.5 |容器:3个满容器

0 个答案:

没有答案