更改`setInterval`中元素的背景颜色

Sen*_*ama 1 html javascript css random

我试图<h1>通过使用document.getElementById("h1").style并使其成为随机颜色的变量来每300毫秒进行一次元素的颜色更改,但它似乎不起作用.

这是我的代码:

function getRandomColor() {
    var letters = '0123456789ABCDEF';
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}
var newColor = getRandomColor();
function color() {
    document.getElementById("h1").style = "backgroundColor = " + newColor;
    setTimeout(color(), 300)
}
Run Code Online (Sandbox Code Playgroud)

gyr*_*yre 6

几点建议:

  • 您不能使用标记名称(h1)作为参数,getElementById除非您在HTML中设置一个(我建议重命名);

  • 您需要使用element.style.backgroundColor = newColor更新CSS样式;

  • color()传递函数后,需要省略括号setTimeout(否则传递该函数的返回值);

  • 你应该getRandomColor在你的颜色功能中调用,这样你每次都会得到不同的颜色;

  • 您可以使用setInterval而不是递归调用setTimeout内部color,因为setInterval可以将额外的参数传递给回调函数,您不需要将其保存<h1>在全局变量中.

编辑:您可以getRandomColor使用JavaScript的原生十六进制字符串转换大幅缩短您的功能:number.toString(16)


演示片段:

function getRandomColor () {
  return '#' + (
    '000000' + (Math.random() * 0x1000000).toString(16)
  ).slice(-6)
}

function color (heading) {
  heading.style.backgroundColor = getRandomColor()
}

setInterval(color, 300, document.getElementById('heading'))
Run Code Online (Sandbox Code Playgroud)
<h1 id="heading">Heading</h1>
Run Code Online (Sandbox Code Playgroud)


aja*_*thi 5

function getRandomColor() {
    var letters = '0123456789ABCDEF';
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

(function color() {
    document.getElementById("myH1").style.backgroundColor = getRandomColor();
    
    //if you want to query element by tag name
    //document.getElementsByTagName("h1")[0].style.backgroundColor = getRandomColor();
    setTimeout(color, 300)
})();
Run Code Online (Sandbox Code Playgroud)
#myH1{
 transition:all 0.3s ease;
}
Run Code Online (Sandbox Code Playgroud)
<h1 id="myH1">test</h1>
Run Code Online (Sandbox Code Playgroud)