requestAnimationFrame实现进度条效果

DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Documenttitle>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      #test {
        width: 0;
        height: 12px;
        border-radius: 12px;
        line-height: 12px;
        background-color: pink;
        margin: 10px;
        cursor: pointer;
      }
    style>
  head>
  <body>
    <div id="test">0%div>
    <script>
      const test = document.querySelector("#test");
      test.addEventListener("click", function () {
        test.style.padding = 8 + "px";
        let timer = requestAnimationFrame(function fn() {
          if (parseInt(test.style.width || 0) < 300) {
            test.style.width = parseInt(test.style.width || 0) + 3 + "px";
            test.innerHTML = parseInt(test.style.width || 0) / 3 + "%";
            timer = requestAnimationFrame(fn);
          } else {
            cancelAnimationFrame(timer);
          }
        });
      });
    script>
  body>
html>

你可能感兴趣的:(css,html,前端)