我创建了一个javascript函数,每隔几秒钟将背景颜色更改为随机颜色,但它不起作用。它会改变点击的颜色,但不会每隔几秒钟改变一次。我想让背景每隔几秒钟改变一次。我正在使用onclick事件在一个div上测试它。我也不想使用jQuery。谢谢你的帮忙!
index.html
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>
<div id="div" onclick="timeChange()"></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<script src="myScript.js">
</script>
</body>
</html>myScript.js
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function changeDivColor() {
var div = document.getElementById("div");
var color = getRandomColor();
div.style.backgroundColor = color;
}
function timeChange() {
window.setInterval(changeDivColor(), 2000);
}main.css
div {
float: left;
width: 200px;
height: 200px;
background-color: black;
margin-bottom: 20px;
margin-right: 20px;
}发布于 2016-03-01 19:39:44
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function changeDivColor() {
var div = document.getElementById("div");
var color = getRandomColor();
div.style.backgroundColor = color;
}
function timeChange() {
window.setInterval(changeDivColor, 2000);
}div {
float: left;
width: 200px;
height: 200px;
background-color: black;
margin-bottom: 20px;
margin-right: 20px;
}<div id="div" onclick="timeChange()"></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
setInterval接受一个函数:
window.setInterval(changeDivColor, 2000);对window.setInterval(changeDivColor(), 2000);
发布于 2016-03-01 19:41:31
在window.onload上创建间隔。我将interval分配给它更改为variable,以后如果需要,可以使用它来清除间隔。
window.onload = function() {
var intervalChange = setInterval(changeDivColor, 2000);
}
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function changeDivColor() {
var div = document.getElementById('div');
var color = getRandomColor();
div.style.backgroundColor = color;
}发布于 2016-03-01 19:35:59
代码中没有div_id:
var div = document.getElementById('div_id');应:
var div = document.getElementById('div');或者您可以更改标签<div id="div" onclick="timeChange()"></div>上的is。
希望这能有所帮助。
https://stackoverflow.com/questions/35731781
复制相似问题