总共4列除以div数

时间:2017-08-01 09:19:39

标签: javascript jquery

如果输入是任意数字并且所有四列都填满整个宽度,我们正在开发小图,它分为四列。

图像: - enter image description here

Html代码: -

<div class="progressArea">
   <div class="leadCon"> Sales Cycle Length <span><b>18</b> days</span></div>
   <div class="proArea">
      <div data-target="1" class="color1">3</div>
      <div data-target="2" class="color2">5</div>
      <div data-target="3" class="color3">7</div>
      <div data-target="4" class="color4">3</div>
   </div>
</div>

jquery代码: -

$(document).ready(function() {
  var totalArea = $('.progressArea .leadCon b').text();
  var divArea = $('.proArea div').width();
  var div = totalArea/4;
  $('.proArea div').css('width', div);  
});

2 个答案:

答案 0 :(得分:0)

  1. 获取所有值的添加
  2. 使用each()并遍历每个数字
  3. 将每个值除以total并将其乘以100,以获取该元素的宽度并使用css()
  4. 将其分配给该元素

    以下是代码:

    $(document).ready(function() {
      createBars('containerId');
      createBars('containerId-2');
    });
    
    function createBars(containerId) {
      var total = 0;
      $('#' + containerId + ' div').each(function() {
        total += parseInt($(this).text());
      });
    
      $('#' + containerId + ' div').each(function() {
        var currentVal = $(this).text();
        var divideResult = (currentVal / total) * 100;
        $(this).css({
          'width': divideResult + '%'
        });
      });
    }
    .proArea {
      float: left;
      width: 100%;
    }
    
    .proArea div {
      text-align: center;
      color: #FFF;
      float: left;
      padding: 4px 0;
    }
    
    .color1 {
      background: red;
    }
    
    .color2 {
      background: blue;
    }
    
    .color3 {
      background: green;
    }
    
    .color4 {
      background: orange;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="progressArea">
      <div class="leadCon"> Sales Cycle Length <span><b>18</b> days</span></div>
      <div class="proArea" id='containerId'>
        <div data-target="1" class="color1">3</div>
        <div data-target="2" class="color2">5</div>
        <div data-target="3" class="color3">7</div>
        <div data-target="4" class="color4">3</div>
      </div>
      <div class="proArea" id='containerId-2'>
        <div data-target="1" class="color1">13</div>
        <div data-target="2" class="color2">25</div>
        <div data-target="3" class="color3">37</div>
        <div data-target="4" class="color4">3</div>
      </div>
    </div>

答案 1 :(得分:0)

在CSS中使用

.color1, .color2, .color3, .color4 { 
    width: 25%; 
    float: left; or display: inline-block;
}