循环遍历值以将宽度指定给div

时间:2018-01-17 11:24:41

标签: javascript jquery html css

我正在处理一个函数,其中使用js动态添加元素的宽度。 这是我的js

<script>
    $('.progress-fill span').each(function(){
        var percent = $(this).html();
        if(percent ==12){
          $(this).parent().css({
            'width' : "100%"
          });
        }
        if(percent ==11){
          $(this).parent().css({
            'width' : "92%"
          });
        }
        if(percent ==10){
          $(this).parent().css({
            'width' : "83%"
          });
        }
        if(percent == 9){
          $(this).parent().css({
            'width' : "75%"
          });
        }
    });
</script>

html看起来像这样:

<div class="results-block">
  <div class="progress-bar">
    <div class="progress-fill">
      <span>12</span>
    </div>
  </div>
</div>

所以我检查.progress-fill span的值,并根据此值设置父div的宽度。这必须从12的可能值下降到1.我目前使用单独的if语句的方式有效,但我确定它不是最有效的方法。有没有人有任何其他想法如何做到这一点?

2 个答案:

答案 0 :(得分:0)

如果我理解你的问题,你有机会计算它。最小值为1,因此等于width: 0%,最大值为12,因此等于width: 100%

<script>
    $('.progress-fill span').each(function(){
        var percent = $(this).html();
        $(this).parent().css({
        'width' : "" + ((percent - 1) * 100) / (12 - 1) + '%'
        });
    });
</script>

答案 1 :(得分:0)

实现这一目标的最简单方法是根据12个可能的值计算宽度百分比,如下所示:

$('.progress-fill').css('width', function() {
  return 100 / 12 * $(this).find('span').text() + '%';
});
.progress-fill {
  background-color: #C00;
  color: #FFF;
  margin: 5px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="results-block">
  <div class="progress-bar">
    <div class="progress-fill">
      <span>12</span>
    </div>

    <div class="progress-fill">
      <span>6</span>
    </div>

    <div class="progress-fill">
      <span>10</span>
    </div>
  </div>
</div>