简体   繁体   English

Javascript自动更改背景颜色不起作用

[英]Javascript Change Background Color automaticly doesn't work

I Want to make a 2 links on a page to: 我想在页面上建立2个链接以:

  • If you click the first one it should change background color every n seconds 如果单击第一个,则应每n秒更改背景颜色
  • The second one should stop this 第二个应该停止

Here is my javascript code that I think should work: 这是我认为应该起作用的JavaScript代码:

var nIntervId;

function changeColor() {
  nIntervId = setInterval(flashColor, 500);
}

function flashColor() {
var oElem = document.getElementById("hidden");

var index = Math.round(Math.random() * 9);
var ColorValue;
if(index == 1)
ColorValue = "FFCCCC";
if(index == 2)
ColorValue = "CCAFFF";
if(index == 3)
ColorValue = "A6BEFF";
if(index == 4)
ColorValue = "99FFFF";
if(index == 5)
ColorValue = "D5CCBB";
if(index == 6)
ColorValue = "99FF99";
if(index == 7)
ColorValue = "FFFF99";
if(index == 8)
ColorValue = "FFCC99";
if(index == 9)
ColorValue = "CCCCCC";
oElem.style.backgroundColor=ColorValue;
}

function stopColor() {
  clearInterval(nIntervId);
}

And here is the html code to call it: 这是调用它的html代码:

<a href="javascript:void(0)" onclick="changeColor();" style="color:#FFF;">Change</a>
<a href="javascript:void(0)" onclick="stopColor();" style="color:#FFF;">STOP</a>

But it doesn't work at all. 但这根本不起作用。 Did I forget anything? 我忘记了什么吗?

Thanks for your help 谢谢你的帮助

Andy 安迪

You need to add a "#" before the color value 您需要在颜色值之前添加“#”

Like "#CCCCCC" 就像“ #CCCCCC”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM