찾다
웹 프론트엔드CSS 튜토리얼CSS를 사용하여 구현된 여러 진행률 표시줄

CSS를 사용하여 구현된 여러 진행률 표시줄

Jan 22, 2021 am 11:10 AM
csscss3CSS3 애니메이션진행률 표시줄

CSS를 사용하여 구현된 여러 진행률 표시줄

(学习视频分享:css视频教程

进度条是一个非常常见的功能,实现起来也不难,一般我们都会用 div 来实现。

作为一个这么常见的需求, whatwg 肯定是不会没有原生组件提供(虽然有我们也不一定会用),那么就让我们来康康有哪些有意思的进度条实现方式。

常规版 — div 一波流

这是比较常规的实现方式,先看效果:

CSS를 사용하여 구현된 여러 진행률 표시줄

源码如下:

<style>
  .progress1 {
    height: 20px;
    width: 300px;
    background-color: #f5f5f5;
    border-bottom-right-radius: 10px;
    border-top-right-radius: 10px;
  }
  .progress1::before {
    counter-reset: progress var(--percent, 0);
    content: counter(progress) &#39;%\2002&#39;;
    display: block;
    height: 20px;
    line-height: 20px;
    width: calc(300px * var(--percent, 0) / 100);
    font-size: 12px;
    color: #fff;
    background-color: #2486ff;
    text-align: right;
    white-space: nowrap;
    overflow: hidden;
    border-bottom-right-radius: 10px;
    border-top-right-radius: 10px;
  }
  .btn {
    margin-top: 30px;
  }
</style>
<div id="progress1" class="progress1"></div>
<button id="btn" class="btn">点我一下嘛~</button>
<script>
  &#39;use strict&#39;;
  let startTimestamp = (new Date()).getTime();
  let currentPercentage = 0;
  let maxPercentage = 100;
  let countDelay = 100;
  let timer = null;
  let start = false;
  const percentageChange = () => {
    const currentTimestamp = (new Date()).getTime();
    if (currentTimestamp - startTimestamp >= countDelay) {
      currentPercentage++;
      startTimestamp = (new Date()).getTime();
      progress1.style = `--percent: ${currentPercentage}`;
    };
    if (currentPercentage < maxPercentage) {
      timer = window.requestAnimationFrame(percentageChange);
    } else {
      window.cancelAnimationFrame(timer);
    };
  };
  const clickHander = () => {
    if (!start) {
      start = true;
      percentageChange();
    };
  };
  btn.addEventListener(&#39;click&#39;, clickHander);
</script>

这种方法的核心就是以当前盒子为容器,以 ::before 为内容填充。用 <div> 的好处就是实现简单,兼容性强,拓展性高,但是美中不足的是标签语义化不强。<h2 id="进阶版-input-type-range">进阶版 — input type="range"</h2> <p><code><input> 是一个非常实用的替换元素,不同的 type 可以做不同的事情。第二种就是用 <input type="range"> 来实现的。首先我们来看看效果:

CSS를 사용하여 구현된 여러 진행률 표시줄

源码如下:

<style>
  .progress2[type=&#39;range&#39;] {
    display: block;    
    font: inherit;
    height: 20px;
    width: 300px;
    pointer-events: none;
    background-color: linear-gradient(to right, #2376b7 100%, #FFF 0%);
  }
  .progress2[type=&#39;range&#39;],
  .progress2[type=&#39;range&#39;]::-webkit-slider-thumb { 
    -webkit-appearance: none;
  };
  .progress2[type=&#39;range&#39;]::-webkit-slider-runnable-track {
    border: none;
    border-bottom-right-radius: 10px;
    border-top-right-radius: 10px;
    height: 20px;
    width: 300px;
  }
  .btn {
    margin-top: 30px;
  }
</style>
<input id="progress2" class="progress2" type=&#39;range&#39; step="1" min="0" max="100" value="0"/>
<button id="btn" class="btn">点我一下嘛~</button>
<script>
  &#39;use strict&#39;;
  let startTimestamp = (new Date()).getTime();
  let currentPercentage = 0;
  let maxPercentage = 100;
  let countDelay = 100;
  let timer = null;
  let start = false;
  let percentageGap = 10;
  const percentageChange = () => {
    const currentTimestamp = (new Date()).getTime();
    if (currentTimestamp - startTimestamp >= countDelay) {
      currentPercentage++;
      startTimestamp = (new Date()).getTime();
      progress2.value = currentPercentage;
      progress2.style.background = `linear-gradient(to right, #2376b7 ${currentPercentage}%, #FFF 0%`;
    };
    if (currentPercentage < maxPercentage) {
      timer = window.requestAnimationFrame(percentageChange);
    } else {
      window.cancelAnimationFrame(timer);
    };
  };
  const clickHander = () => {
    if (!start) {
      start = true;
      percentageChange();
    };
  };
  btn.addEventListener(&#39;click&#39;, clickHander);
</script>

写完这个 demo 才发现,<input type="range"> 并不适合做这个功能。。一个是实现困难,这个 type 组件的每个元件都可以单独修改样式,但是效果并不是很好。

另一个是因为 range 有专属语意 —— 范围,所以它更适合做下面这种事:

CSS를 사용하여 구현된 여러 진행률 표시줄

以上demo来自:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/range

高级版 — progress 鸭

当然,上述两种方式都是模拟进度条,实际上我们并不需要模拟,因为 whatwg 有为我们提供原生的进度条标签 —— <progress></progress>

我们先看效果:

CSS를 사용하여 구현된 여러 진행률 표시줄

实现如下:

<style>
  .progress3 {
    height: 20px;
    width: 300px;
    -webkit-appearance: none;
    display: block;
  }
  .progress3::-webkit-progress-value {
    background: linear-gradient(
      -45deg, 
      transparent 33%, 
      rgba(0, 0, 0, .1) 33%, 
      rgba(0,0, 0, .1) 66%, 
      transparent 66%
    ),
      linear-gradient(
        to top, 
        rgba(255, 255, 255, .25), 
        rgba(0, 0, 0, .25)
      ),
      linear-gradient(
        to left,
        #09c,
        #f44);
    border-radius: 2px; 
    background-size: 35px 20px, 100% 100%, 100% 100%;
  }
  .btn {
    margin-top: 30px;
  }
</style>
<progress id="progress3" class="progress3" max="100" value="0"></progress>
<button id="btn" class="btn">点我一下嘛~</button>
<script>
  &#39;use strict&#39;;
  let startTimestamp = (new Date()).getTime();
  let currentPercentage = 0;
  let maxPercentage = 100;
  let countDelay = 100;
  let timer = null;
  let start = false;
  const percentageChange = () => {
    const currentTimestamp = (new Date()).getTime();
    if (currentTimestamp - startTimestamp >= countDelay) {
      currentPercentage++;
      startTimestamp = (new Date()).getTime();
      progress3.setAttribute(&#39;value&#39;, currentPercentage);
    };
    if (currentPercentage < maxPercentage) {
      timer = window.requestAnimationFrame(percentageChange);
    } else {
      window.cancelAnimationFrame(timer);
    };
  };
  const clickHander = () => {
    if (!start) {
      start = true;
      percentageChange();
    };
  };
  btn.addEventListener(&#39;click&#39;, clickHander);
</script>

虽然有原生的进度条标签,但是规范里并没有规定它的具体表现,所以各个浏览器厂商完全可以按照自己的喜好去定制,样式完全不可控,所以标签虽好。。可用性却不强,有点可惜。

终极版 — meter 赛高

当然,能够实现进度条功能的标签,除了上面所说的,还有 <meter></meter> 标签。先看效果:

CSS를 사용하여 구현된 여러 진행률 표시줄

代码如下:

<style>
  .progress4 {
    display: block;    
    font: inherit;
    height: 50px;
    width: 300px;
    pointer-events: none;
  }
  .btn {
    margin-top: 30px;
  }
</style>
<meter id="progress4" class="progress4" low="60" high="80" min="0" max="100" value="0"></meter>
<button id="btn" class="btn">点我一下嘛~</button>
<script>
  &#39;use strict&#39;;
  let startTimestamp = (new Date()).getTime();
  let currentPercentage = 0;
  let maxPercentage = 100;
  let countDelay = 100;
  let timer = null;
  let start = false;
  const percentageChange = () => {
    const currentTimestamp = (new Date()).getTime();
    if (currentTimestamp - startTimestamp >= countDelay) {
      currentPercentage++;
      startTimestamp = (new Date()).getTime();
      progress4.value = currentPercentage;
    };
    if (currentPercentage < maxPercentage) {
      timer = window.requestAnimationFrame(percentageChange);
    } else {
      window.cancelAnimationFrame(timer);
    };
  };
  const clickHander = () => {
    if (!start) {
      start = true;
      percentageChange();
    };
  };
  btn.addEventListener(&#39;click&#39;, clickHander);
</script>

这个标签可能比较陌生,实际上它跟 <input type="range"> 的语义是一样的,用来显示已知范围的标量值或者分数值。不一样的就是。。。它样式改起来更麻烦。

总结

本文测评了4种实现进度条的方式,得出的结论就是 —— <div> 赛高。。。虽然有的时候想优雅一点追求标签语义化,但是资源不支持,也很尴尬。<p>嗯,万能的 <code><div> 。<p>以上 demo 都可以我的 codepen 上查看:https://codepen.io/krischan77/pen/QPezjB</p> <p>更多编程相关知识,请访问:<a href="https://www.php.cn/course.html" target="_blank" textvalue="编程视频">编程视频</a>!!</p> </div>

위 내용은 CSS를 사용하여 구현된 여러 진행률 표시줄의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
이 기사는 segmentfault에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제
커서를위한 다음 레벨 CSS 스타일커서를위한 다음 레벨 CSS 스타일Apr 23, 2025 am 11:04 AM

CSS가있는 커스텀 커서는 훌륭하지만 JavaScript를 사용하여 다음 단계로 가져갈 수 있습니다. JavaScript를 사용하면 커서 상태를 전환하고 커서 내에 동적 텍스트를 배치하고 복잡한 애니메이션을 적용하며 필터를 적용 할 수 있습니다.

Worlds Collide : 스타일 쿼리를 사용한 KeyFrame Collision DetectionWorlds Collide : 스타일 쿼리를 사용한 KeyFrame Collision DetectionApr 23, 2025 am 10:42 AM

2025 년에 서로를 ricocheting하는 요소가있는 대화식 CSS 애니메이션은 CSS에서 Pong을 구현할 필요가 없지만 CSS의 유연성과 힘이 증가하는 것은 LEE의 의심을 강화합니다.

UI 효과를 위해 CSS 배경 필터 사용UI 효과를 위해 CSS 배경 필터 사용Apr 23, 2025 am 10:20 AM

CSS 배경 필터 속성을 사용하여 사용자 인터페이스 스타일에 대한 팁과 요령. 여러 요소들 사이에 필터를 배경으로 배경으로 배경으로하는 방법을 배우고 다른 CSS 그래픽 효과와 통합하여 정교한 디자인을 만듭니다.

미소?미소?Apr 23, 2025 am 09:57 AM

글쎄, SVG '의 내장 애니메이션 기능은 계획대로 이상 사용되지 않았다. 물론 CSS와 JavaScript는 부하를 운반 할 수있는 것 이상이지만 Smil이 이전과 같이 물에서 죽지 않았다는 것을 아는 것이 좋습니다.

'예쁜'은 보는 사람의 눈에 있습니다'예쁜'은 보는 사람의 눈에 있습니다Apr 23, 2025 am 09:40 AM

예, 텍스트-랩을위한 점프 : Safari Technology Preview의 예쁜 착륙! 그러나 Chromium 브라우저에서 작동하는 방식과는 다른 점을 조심하십시오.

CSS- 트릭 연대기 XLIIICSS- 트릭 연대기 XLIIIApr 23, 2025 am 09:35 AM

이 CSS- 트릭 업데이트는 Almanac, 최근 Podcast 출연, 새로운 CSS 카운터 가이드 및 귀중한 컨텐츠에 기여하는 몇 가지 새로운 저자의 추가 진전을 강조합니다.

Tailwind ' s @apply 기능은 소리보다 낫습니다Tailwind ' s @apply 기능은 소리보다 낫습니다Apr 23, 2025 am 09:23 AM

대부분의 경우 사람들은 Tailwind ' S 단일 프로퍼 유틸리티 중 하나 (단일 CSS 선언을 변경)와 함께 Tailwind ' s @apply 기능을 보여줍니다. 이런 식으로 선보일 때 @apply는 전혀 약속하는 소리가 들리지 않습니다. 그래서 Obvio

릴리스가없는 느낌 : 제정신 배치를 향한 여정릴리스가없는 느낌 : 제정신 배치를 향한 여정Apr 23, 2025 am 09:19 AM

바보처럼 배포하는 것은 배포하는 데 사용하는 도구와 복잡성에 대한 보상과 복잡성이 추가됩니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

에디트플러스 중국어 크랙 버전

에디트플러스 중국어 크랙 버전

작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

mPDF

mPDF

mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.