Vanilla JS希望在每次点击时创建一个新的进度栏?

时间:2018-12-02 22:36:50

标签: javascript dom

我有这个进度条,它是在单击时在2秒钟的setTimeout中创建的。 现在,我想在每次单击时创建一个新的进度条并将其附加到DOM。我怎么做?我尝试使用Promise,但是在setTimeout之后才得到解决-不知道它是否在做任何事情。我可以在这里使用请求动画帧吗?

(function() {
  const container = document.getElementById('container');

  const addBtn = document.getElementById('add');

  const progress = document.getElementsByClassName('progress');

  let promise = Promise.resolve();


  document.addEventListener('click', function(e) {
    // clone the progress made so far
    const newProgress = Object.assign({}, progress);

    // now add the new progress into container element, so its visible
    container.appendChild(newProgress[0]);

    promise = promise.then(() => new Promise((resolve) => {
      setTimeout(() => {
        newProgress[0].classList.add('active');
        console.log(newProgress[0].classList)
        setTimeout(() => {
          resolve();
        }, 2000);
      }, 0);
    }));
  });

})();
#container {
  margin: 20px;
}

.progress {
  margin: 0 0 10px;
  width: 500px;
  height: 20px;
  background-color: #e0e0e0;
}

.progress .bar {
  width: 0;
  height: 100%;
  background-color: lightgreen;
  transition: width 2s ease;
}

.progress.active .bar {
  width: 100%;
}
<button id="add">Add</button>

<div id="container"></div>

<div style="display: none">
  <div class="progress">
    <div class="bar"></div>
  </div>
</div>

1 个答案:

答案 0 :(得分:1)

建议复制DOM节点(即与.progress匹配的节点)的方法是使用.cloneNode()方法。对于您的代码,您还希望将true传递给.cloneNode(),以确保也克隆了进度节点的子代。

因此,如果我正确理解了您的问题,那么您想克隆进度节点,然后延迟将.active类分配给克隆。这可以通过对代码进行以下修改来实现:

(function(){
  const container = document.getElementById('container');

  const addBtn = document.getElementById('add');

  // use querySelector to aquire progress node for subsequent cloning
  const progress = document.querySelector('.progress');

  addBtn.addEventListener('click', function(e) {

    // use cloneNode to duplicate existing node on DOM rather than 
    // Object.assign as you currently are
    const newProgress =  progress.cloneNode(true);
    
    container.appendChild(newProgress);
      
    // delay assignment of '.active' class to clone
    setTimeout(() => {    
      newProgress.classList.add('active');
    }, 50); 
  });
})();
#container {
  margin: 20px;
}

.progress {
  margin: 0 0 10px;
  width: 500px;
  height: 20px;
  background-color: #e0e0e0;
}

.progress .bar {
  width: 0%;
  height: 100%;
  background-color: lightgreen;
  transition: width 2s ease;
}

.progress.active .bar {
  width: 100%;
}
<button id="add">Add</button>

<div id="container"></div>

<div style="display: none">
  <div class="progress">
    <div class="bar"></div>
  </div>
</div>