<style>
  * {
    margin: 0;
    padding: 0;
  }

  .box {
    display: flex;
    align-items: flex-end;
    width: 1200px;
    height: 200px;
    border: 3px solid skyblue;
    margin: 100px auto;
  }

  .box div {
    /* border: solid 1px skyblue; */
    background-color: salmon;
    height: 100px;
  }
</style>
<body>
  <div class='box'>
  </div>
</body>
<script>
  window.onload = function() {
    let num = prompt('输入柱状图数量');
    let box = document.querySelector('.box');
    let boxW = box.clientWidth;
    let sumNum = boxW / num;
    for (let index = 1; index <= num; index++) {
      let div = document.createElement('div');
      div.style.height = sumNum + 'px';
      if (index !== num) {
        div.style.marginRight = sumNum + 'px';
      }
      box.appendChild(div);
    }
  };
</script>
这段代码中存在以下问题:
<ol>
<li>需要将代码放在<code>&lt;script&gt;</code>标签中,而不是放在<code>&lt;style&gt;</code>标签中。</li>
<li>在<code>let boxW = box.clientWidth</code>之前,需要确保DOM元素已经加载完成,可以将代码放在<code>window.onload</code>事件中。</li>
<li><code>sumNum</code>的计算公式有误,应该是<code>boxW / num</code>,而不是<code>boxW / (3 + (2 * num - 2))</code>。</li>
<li>在创建新的<code>div</code>元素时,应该设置<code>div.style.height</code>,而不是<code>div.style.width</code>。</li>
<li>在循环中,应该设置每个<code>div</code>元素的<code>margin-right</code>,而不是<code>margin-left</code>。</li>
</ol>
<p>修正后的代码如下:</p>
<pre><code class="language-html">&lt;style&gt;
  * {
    margin: 0;
    padding: 0;
  }

  .box {
    display: flex;
    align-items: flex-end;
    width: 1200px;
    height: 200px;
    border: 3px solid skyblue;
    margin: 100px auto;
  }

  .box div {
    /* border: solid 1px skyblue; */
    background-color: salmon;
    height: 100px;
  }
&lt;/style&gt;

&lt;body&gt;
  &lt;div class='box'&gt;

  &lt;/div&gt;
&lt;/body&gt;
&lt;script&gt;
  window.onload = function() {
    let num = prompt('输入柱状图数量');
    let box = document.querySelector('.box');
    let boxW = box.clientWidth;
    let sumNum = boxW / num;
    for (let index = 1; index &lt;= num; index++) {
      let div = document.createElement('div');
      div.style.height = sumNum + 'px';
      if (index !== num) {
        div.style.marginRight = sumNum + 'px';
      }
      box.appendChild(div);
    }
  };
&lt;/script&gt;
</code></pre>
JavaScript 柱状图绘制代码分析及优化

原文地址: https://www.cveoy.top/t/topic/buwu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录