如何使用JavaScript创建一个颜色渐变的文本效果?

3
我正在尝试制作一个每400毫秒更换颜色的渐变。我使用了别人的随机颜色更改器,并将其添加到h1标签中,以便进行更改。当我没有使用渐变时,它可以正常工作,但是一旦我尝试添加渐变,它就完全无法工作。这是我的代码没有渐变:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Word Animation</title>
    <style>
        body {
            background-color: black;
        }
        h1 {
            transition:300ms;
            text-align: center;
            vertical-align: middle;
            font-size: 200px;
            font-family: Impact, Arial,serif;
        }
    </style>
</head>
<body>
  <h1 id="h1">RANDOM TEXT</h1>
  <script>
      function getRandomColor() {
          var letters = '0123456789ABCDEF';
          var color = '#';
          for (var i = 0; i < 6; i++ ) {
              color += letters[Math.floor(Math.random() * 16)];
          }
          return color;
      }
      function title() {
          document.getElementById("h1").style.color = getRandomColor();
          setTimeout(title, 300);
      }
      title();
  </script>
</body>
</html>

这个可以实现,但是它带有渐变效果:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Word Animation</title>
  <style>
    body {
      background-color: black;
    }
    h1 {
      transition: 300ms;
      text-align: center;
      vertical-align: middle;
      font-size: 200px;
      font-family: Impact, Arial, serif;
      background: -webkit-linear-gradient(blue, red);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
    }
  </style>
</head>

<body>
  <h1 id="h1">RANDOM TEXT</h1>
  <script>
    function getRandomColor() {
      var letters = '0123456789ABCDEF';
      var color = '#';
      for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
      }
      return color;
    }

    function title() {
      document.getElementById("h1").style.background = "-webkit-linear-gradient(", getRandomColor(), ",", getRandomColor();
      setTimeout(title, 300);
    }
    title();
  </script>
</body>

</html>

请帮忙,谢谢!


请注意,如果您使用mix-blend-mode,则可能也适用于Firefox。http://codepen.io/gc-nomade/pen/ENggbv - G-Cyrillus
2个回答

2

您需要设置:

background: -webkit-linear-gradient(red, blue);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;

一起操作(我不知道为什么??,但它对我有用);

JS

var s = document.createElement("style");
document.getElementsByTagName("head")[0].appendChild(s);
function title() {
  s.innerHTML = "h1 {\n\
        background: -webkit-linear-gradient(" + getRandomColor() + ", " + getRandomColor() + ");\n\
        -webkit-background-clip: text;\n\
        -webkit-text-fill-color: transparent;\n\
    }";
  setTimeout(title, 300);
}
title();

1
你需要使用加号而不是逗号来连接字符串。
var col = "-webkit-linear-gradient(" + getRandomColor() + ", " + getRandomColor() + ")";
document.getElementById("h1").style.background = col;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接