计时器上的变色文字?(HTML)

空用户

我需要用两个按钮和一些文本制作一个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') {

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章