定时器上的变色文本?(网页版)

Color-changing text on timer? (HTML)

本文关键字:网页 文本 定时器      更新时间:2023-09-26

我需要制作一个带有两个按钮和一些文本的HTML脚本,其中第一个按钮激活循环计时器,循环切换不同颜色的文本;另一个按钮中断计时器。

我试图扭动程序但没有运气:

<button type="button" onclick="startCycle()">Start/Resume cycle</button>
<button type="button" onclick="stopCycle()">Stop cycle</button>
<div id="title">Colormatic!</div>
It is currently
<p id="indicator"></p>
<script>
var timerId;
var color = 0;
var colors = ['blue', 'green', 'yellow'];
document.getElementById("title").style.color = colors;
document.getElementById("indicator").innerHTML = colors;
function startCycle() {
    timerId = setInterval(changeColor, 1000);
}
function stopCycle() {
    clearInterval(timerId);
    timerId = null;
}
function changeColor() {
    if(document.getElementById("indicator").innerHTML == 'blue') {
        document.getElementById("title").style.color = colors[1];
        document.getElementById("indicator").innerHTML = colors[1];
    } else if(document.getElementById("indicator"). == 'green') {
        document.getElementById("title").style.color = colors[2];
        document.getElementById("indicator").innerHTML = colors[2];
    } else {
        document.getElementById("title").style.color = colors[0];
        document.getElementById("indicator").innerHTML = colors[0];
    }
}
</script>

在这里,按钮"开始/恢复循环"应该执行功能startCycle(),按钮"停止循环"函数stopCycle(),分别启动和停止计时器。

计时器执行功能changeColor,该函数旨在查看"指示器"段落显示的颜色,从而将"标题"分区重新着色为列表中的下一个颜色。

我想我本可以检测到"标题"分区的实际颜色,而不是创建一个新段落。这和一大堆我本可以改进的东西。

什至敢打赌,我在这里做了很多错误的事情。

提前感谢您抽出时间!

更新:我终于让它工作了。 在此处查看完整代码:

<button type="button" onclick="startCycle()">Start/Resume cycle</button>
<button type="button" onclick="stopCycle()">Stop cycle</button>
<div id="title">Colormatic!</div>
It is currently
<span id="indicator">blue</span>
<script>
var timerId;
var ind = document.getElementById("indicator");
var tit = document.getElementById("title");
var color = ["red"]
function startCycle() {
    timerId = setInterval(changeColor, 500);
}
function stopCycle() {
    clearInterval(timerId);
    timerId = null;
}
function changeColor() {
    if (ind.innerHTML == 'blue') {
        tit.style.color = 'green';
        ind.innerHTML = 'green';
    }
    else if (ind.innerHTML == "green") {
        tit.style.color = 'yellow';
        ind.innerHTML = "yellow";
    }
    else {
        tit.style.color = 'blue';
        ind.innerHTML = "blue";
    }
}
</script>

31 行:} else if(document.getElementById("indicator"). == 'green') {

需要:

} else if(document.getElementById("indicator").innerHTML == 'green') {

这只是一个错字。使用浏览器开发人员工具中的控制台来捕获此类编译时错误。