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

时间:2017-03-15 18:45:03

标签: javascript html css random

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

这是我的代码:

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)
}

4 个答案:

答案 0 :(得分:5)

&#13;
&#13;
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)
})();
&#13;
#myH1{
 transition:all 0.3s ease;
}
&#13;
<h1 id="myH1">test</h1>
&#13;
&#13;
&#13;

答案 1 :(得分:5)

一些指示:

  • 您不能使用标记名称(#include <Wire.h> #include <Adafruit_PWMServoDriver.h> //default address Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver(); class Quadruped_Robot{ private: //minimum and maximum pulse length count //valid range: [0,4096] //0 degrees: 200 //60 degrees: 360 //90 degrees: 510 //180 degrees: 915 size_t SERVOMIN= 200; size_t SERVOMAX= 915; //phase shift between upper and lower leg actuation in milliseconds size_t OFFSET= 1000; //pulse length to servo motors size_t PULSE_LENGTH= 100; struct Leg{ int channels[2]; bool started; virtual void foo()=0; }; struct fRight:Leg{ //channel numbers on the PWM/Servo driver for the front right leg //0= upper leg //1= lower leg int channels[2]= {0, 1}; bool started= false; virtual void foo(){} }; struct fLeft:Leg{ //channel numbers on the PWM/Servo driver for the front left leg //2= upper leg //3= lower leg int channels[2]= {2, 3}; bool started= false; virtual void foo(){} }; struct bRight:Leg{ //channel numbers on the PWM/Servo driver for the back right leg //4= upper leg //5= lower leg int channels[2]= {4, 5}; bool started= false; virtual void foo(){} }; struct bLeft:Leg{ //channel numbers on the PWM/Servo driver for the back left leg //6= upper leg //7= lower leg int channels[2]= {6, 7}; bool started= false; virtual void foo(){} }; //bool value indicating whether the servos have begun moving bool started= false; //holds the previous timestamp unsigned long prevTime; public: Leg* myLegs[4]= {new fRight, new fLeft, new bRight, new bLeft}; void actuateLeg(size_t leg){ prevTime= millis(); Leg *myLeg= myLegs[leg]; size_t PWM= SERVOMIN; //Actuate upper leg and wait until the phase shift time has elapsed to actuate the lower leg while(millis()-prevTime < OFFSET){ pwm.setPWM(myLeg->channels[0], 0, PWM ); Serial.println(myLeg->channels[0]); } prevTime= millis(); //Actuate lower leg and wait until the phase shift time has elapsed to actuate the upper leg again while(millis()-prevTime < OFFSET){ pwm.setPWM(myLeg->channels[1], 0, PWM ); Serial.println(myLeg->channels[1]); } prevTime= millis(); PWM= SERVOMAX; //Actuate upper leg and wait until the phase shift time has elapsed to actuate the lower leg again while(millis()-prevTime < OFFSET){ pwm.setPWM(myLeg->channels[0], 0, PWM ); Serial.println(myLeg->channels[0]); } prevTime= millis(); while(millis()-prevTime < OFFSET){ pwm.setPWM(myLeg->channels[1], 0, PWM ); Serial.println(myLeg->channels[1]); } delete myLeg; } void walk(){ actuateLeg(0); actuateLeg(2); actuateLeg(1); actuateLeg(3); } }; //Create a Quadruped_Robot object Quadruped_Robot myQuadruped; void setup() { //Begin serial communication at 9600 bps Serial.begin(9600); //MG996R servo runs at 50 Hz pwm.setPWMFreq(50); pwm.begin(); } void loop() { myQuadruped.walk(); } )作为h1的参数,除非您在HTML中设置了一个(我建议重命名);

  • 您需要使用getElementById来更新CSS样式;

  • 当您将函数传递给element.style.backgroundColor = newColor时,您需要在color()之后省略括号(否则您将传递该函数的返回值); < / p>

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

  • 您可以使用getRandomColor代替在setInterval内递归调用setTimeout,并且由于color可以将额外参数传递给您的回调函数,因此您不需要setInterval。需要将<h1>保存在全局变量中。

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

<小时/>

演示片段:

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

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

setInterval(color, 300, document.getElementById('heading'))
&#13;
<h1 id="heading">Heading</h1>
&#13;
&#13;
&#13;

答案 2 :(得分:2)

更改

document.getElementById("h1").style = "backgroundColor = " + newColor;

document.getElementById("h1").style.backgroundColor = + newColor;

此代码未经测试,但backgroundColor是样式的属性,因此它应为style.backgroundColor而不是style = backgroundColor

修改

正如另一个答案所提到的,h1不能是getElementById的属性,所以给你的h1一个Id或者用另一种方法选择它。

答案 3 :(得分:0)

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

setInterval(function() {
   document.getElementsByTagName('h1')[0].style.backgroundColor = getRandomColor();
}, 300)