首页 > 解决方案 > 如何通过过渡元素在 CSS 中创建进度条

问题描述

您好如何通过过渡元素在 CSS 中创建进度条。

.pro {
    height: 2px;
    width: 100vw;
    transition: width 2s ease-in-out;
    background-color: red;
  }

标签: cssprogress-barcss-transitionsloading

解决方案


你可以用keyframes这个。

const btn = document.querySelector('.btn'), pro = document.querySelector('.pro')

btn.addEventListener('click', function() {
  
  pro.classList.remove('progress');
  
  addPro();
  
});

function addPro() {
  setTimeout(function() {
    pro.classList.add('progress');
  }, 200)
}
*{
  box-sizing: border-box;
}

.wrapper {
  width: 95%;
  margin: 50px auto;
}
.pro {
  height: 2px;
  width: 0;
  max-width: 100%;
  background-color: red;
}

.pro.progress {
  animation: progress 1.75s ease-in-out forwards;
}

@keyframes progress {
  from{
    width: 0;
  }to {
    width: 100vw;
  }   
}
  
.btn {
  display: inline-block;
  padding: 10px 20px;
  background: red;
  color: #fff;
  cursor: pointer;
}
<div class="wrapper">
  <div class="pro progress"></div>
</div>

<div class="btn">show animation again</div>


推荐阅读