搜尋

首頁  >  問答  >  主體

是否可以實現從一種顏色繪製的文字到動畫漸變的平滑過渡?

頁面上有白色文本,其下方有一個按鈕。此外,也套用動畫漸層來填滿文字。單擊該按鈕時,-webkit-text-fill-color 屬性將變為透明,從而導致文字顏色突然變化以匹配漸變。

如下:https://codepen.io/hvyjhqnt-the-vuer/pen/poQdaLQ

能否實現從白色到漸變的平滑過渡? (-webkit-text-fill-color 屬性不直接支援transition

P粉762447363P粉762447363469 天前830

全部回覆(1)我來回復

  • P粉465287592

    P粉4652875922023-09-17 00:50:46

    CSS 顏色屬性是可轉換的,因此請使用它。

    <head>
      <meta charset="UTF-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <title>Smooth color change in js</title>
      <link rel="stylesheet" href="css/styles.css" />
      <style>
        @font-face {
          font-family: Alice;
          src: local(Alice), url(../fonts/Alice-Regular.ttf);
        }
        
        html {
          height: 100%;
        }
        
        body {
          text-align: center;
          justify-content: center;
          align-items: center;
          background-color: #201e1e;
        }
        
        h1 {
          font-family: Alice;
          font-size: 7vw;
          background: linear-gradient(45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
          -webkit-background-clip: text;
          background-clip: text;
          color: white;
          transition: color 5s linear;
          background-size: 500% 500%;
          animation: textShine 5s ease-in-out infinite alternate;
        }
        
        button {
          font-family: Alice;
          font-size: 20px;
          padding: 10px 20px;
          background-color: #201e1e;
          color: white;
          border: 2px solid white;
          cursor: pointer;
          transition: background-color 0.3s ease;
        }
        
        button:hover {
          background: linear-gradient(45deg, #38292c, #362d31, #363c3d, #2f3026);
        }
        
        @keyframes textShine {
          0% {
            background-position: 0% 50%;
          }
          100% {
            background-position: 100% 50%;
          }
        }
      </style>
    
    </head>
    
    <body>
      <h1 id="my-text" class="show">Hello word</h1>
      <button id="button" onclick="changeColor()">Переливайся</button>
      <script src="script.js"></script>
    </body>
    <script>
      let col;
    
      function changeColor() {
        const myText = document.getElementById("my-text");
        const computedStyle = window.getComputedStyle(myText);
        const textColor = computedStyle.getPropertyValue("color");
    
        if (textColor === "rgb(255, 255, 255)") {
          col = "transparent";
          document.getElementById("button").innerHTML = "Не переливайся";
        } else {
          col = "white";
          document.getElementById("button").innerHTML = "Переливайся";
        }
    
        myText.style.color = col;
      }
    </script>

    回覆
    0
  • 取消回覆