我试图制作一个每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>
&#13;
这样可行,但这是 渐变:
<!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>
&#13;
请帮忙。在此先感谢:)
答案 0 :(得分:0)
您需要使用加号连接字符串,而不是逗号。
var col = "-webkit-linear-gradient(" + getRandomColor() + ", " + getRandomColor() + ")";
document.getElementById("h1").style.background = col;
答案 1 :(得分:0)
您需要设置:
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();