我正在尝试制作可以改变颜色的div.这是我的代码:
window.onload = function () {
for (;;){
setTimeout(function () {
document.querySelector('style').style.backgroundColor = colors[rand(colors.length)];
}, 2000);
}
}
var colors = [
'red',
'green',
'blue',
'yellow',
'magenta',
'pink'
];
var rand = function (max) {
return Math.floor(Math.random() * max);
};Run Code Online (Sandbox Code Playgroud)
.style{
background-color: pink;
top: 50px;
left: 50px;
height: 50px;
width: 50px;
}Run Code Online (Sandbox Code Playgroud)
<body>
<div class="style"></div>
</body>Run Code Online (Sandbox Code Playgroud)
但我无法找出它为什么不起作用.
编辑:该脚本也崩溃了浏览器
假设你的标记是这样的:
<body>
<div id="my-id"></div>
</body>
Run Code Online (Sandbox Code Playgroud)
要创建"颜色循环",您必须使用setInterva()设置一个无限次执行的函数(使用定义的间隔)来更改颜色.这是正确的代码:
var cur_color = -1,
colors = [
'red',
'green',
'blue',
'yellow',
'magenta',
'pink'
];
var myInterval = setInterval(function() {
document.getElementById('my-id').style.backgroundColor = colors[(++cur_color) % colors.length];
}, 2000);
Run Code Online (Sandbox Code Playgroud)
这将每2秒更改一次颜色.如果要停止它,可以使用以下clearInterval()功能:
clearInterval(myInterval);
Run Code Online (Sandbox Code Playgroud)
假设你的标记是:
<body>
<div class="my-class"></div>
<div class="my-class"></div>
<div class="my-class"></div>
</body>
Run Code Online (Sandbox Code Playgroud)
您可以使用该getElementsByClassName()方法:
var myInterval = setInterval(function() {
var elements = document.getElementsByClassName('my-class');
++cur_color;
for (var i=0; i<elements.length; i++) elements[i].style.backgroundColor = colors[cur_color % colors.length];
}, 2000);
Run Code Online (Sandbox Code Playgroud)
这是一个包含多个元素的工作示例:
var cur_color = -1,
colors = [
'red',
'green',
'blue',
'yellow',
'magenta',
'pink'
];
var myInterval = setInterval(function () {
var elements = document.getElementsByClassName('my-class');
++cur_color;
for (var i = 0; i < elements.length; i++) elements[i].style.backgroundColor = colors[cur_color % colors.length];
}, 2000);Run Code Online (Sandbox Code Playgroud)
.my-class {
background-color: pink;
top: 50px;
left: 50px;
height: 50px;
width: 50px;
margin: 10px;
}Run Code Online (Sandbox Code Playgroud)
<body>
<div class="my-class"></div>
<div class="my-class"></div>
<div class="my-class"></div>
<body>Run Code Online (Sandbox Code Playgroud)