gpt4 book ai didi

javascript - 再次输入后更改文本颜色效果?

转载 作者:搜寻专家 更新时间:2023-10-31 08:51:10 26 4
gpt4 key购买 nike

我正在为我的网站使用从 codepen 获得的这种打字轮播效果,但是,我需要帮助来修改它。现在,它所做的一切都是在一个单词列表中循环并输入它们。

我想要的效果是每个单独的单词的文本颜色是不同的。话:

  • Nerd 。
  • 简单。
  • 纯 JS。
  • 漂亮。
  • 有趣!

打出来的时候都是不同的颜色。我怎样才能做到这一点?

Codepen Example

var TxtRotate = function(el, toRotate, period) {
this.toRotate = toRotate;
this.el = el;
this.loopNum = 0;
this.period = parseInt(period, 10) || 2000;
this.txt = '';
this.tick();
this.isDeleting = false;
};

TxtRotate.prototype.tick = function() {
var i = this.loopNum % this.toRotate.length;
var fullTxt = this.toRotate[i];

if (this.isDeleting) {
this.txt = fullTxt.substring(0, this.txt.length - 1);
} else {
this.txt = fullTxt.substring(0, this.txt.length + 1);
}

this.el.innerHTML = '<span class="wrap">' + this.txt + '</span>';

var that = this;
var delta = 300 - Math.random() * 100;

if (this.isDeleting) {
delta /= 2;
}

if (!this.isDeleting && this.txt === fullTxt) {
delta = this.period;
this.isDeleting = true;
} else if (this.isDeleting && this.txt === '') {
this.isDeleting = false;
this.loopNum++;
delta = 500;
}

setTimeout(function() {
that.tick();
}, delta);
};

window.onload = function() {
var elements = document.getElementsByClassName('txt-rotate');
for (var i = 0; i < elements.length; i++) {
var toRotate = elements[i].getAttribute('data-rotate');
var period = elements[i].getAttribute('data-period');
if (toRotate) {
new TxtRotate(elements[i], JSON.parse(toRotate), period);
}
}
// INJECT CSS
var css = document.createElement("style");
css.type = "text/css";
css.innerHTML = ".txt-rotate > .wrap { border-right: 0.08em solid #666 }";
document.body.appendChild(css);
};
html,
body {
font-family: 'Raleway', sans-serif;
padding: 1em 2em;
font-size: 18px;
background: #222;
color: #aaa
}

h1,
h2 {
font-weight: 200;
margin: 0.4em 0;
}

h1 {
font-size: 3.5em;
}

h2 {
color: #888;
font-size: 2em;
}
<link href="https://fonts.googleapis.com/css?family=Raleway:200,100,400" rel="stylesheet" type="text/css" />
<h1>This pen is
<span class="txt-rotate" data-period="2000" data-rotate='[ "nerdy.", "simple.", "pure JS.", "pretty.", "fun!" ]'></span>
</h1>
<h2>A single &lt;span&gt; is all you need.</h2>

最佳答案

您可以通过定义一组颜色来做到这一点:

var colours = ["red", "green", "blue", "yellow", "orange"]

并在每个循环中设置它:

this.el.innerHTML = '<span class="wrap" style="color: ' + colours[i] + '">'+this.txt+'</span>';

fork 示例:https://codepen.io/mark_c/pen/WEavqy?editors=1010

关于javascript - 再次输入后更改文本颜色效果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45911765/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com