是否可以实现从一种颜色绘制的文本到动画渐变的平滑过渡?
P粉762447363
P粉762447363 2023-09-16 09:22:05
0
1
780

页面上有白色文本,其下方有一个按钮。此外,还应用动画渐变来填充文本。单击该按钮时,-webkit-text-fill-color 属性将变为透明,从而导致文本颜色突然发生变化以匹配渐变。

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

能否实现从白色到渐变的平滑过渡? (-webkit-text-fill-color 属性不直接支持transition

P粉762447363
P粉762447363

全部回复(1)
P粉465287592

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>
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!