我正在尝试创建一个简单的 JavaScript 脚本,该脚本会每 500 毫秒闪烁一次不同颜色的文本。我想到了类似的东西,但它不起作用,它只是以单一颜色打印出文本(绿色,黑色或红色三种之一)。感谢您的帮助
<html>
<body >
<script>
var f = function() {
var str = "Hello World";;
var d = new Date();
var n = d.getTime();
switch(n%3)
{
case 1:
fontcolor="green"
break;
case 2:
fontcolor="black"
break;
default:
fontcolor="red"
}
document.write(str.fontcolor(fontcolor));
}
setInterval(f, 500);
</script>
</body>
</html>
最佳答案
尝试这样的事情(请参阅评论以了解发生了什么):
// Wait until the document is ready
window.onload = function()
{
// Create the element
var txt = document.createElement('span');
txt.innerHTML = 'Hello World!';
// Insert the element to the document
document.body.appendChild(txt);
// Alternate the colors
var colors = [ 'red', 'green', 'blue', 'black', 'yellow', 'pink' ];
var current = 0;
setInterval(function()
{
// Update element's style with the new color
txt.style.color = colors[current];
// Go to the next color
current = (current + 1) % colors.length;
}, 500);
};
关于javascript - 每 500 毫秒闪烁不同颜色的文本 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15693513/