Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么不是';这不是在改变背景吗?_Javascript_Css - Fatal编程技术网

Javascript 为什么不是';这不是在改变背景吗?

Javascript 为什么不是';这不是在改变背景吗?,javascript,css,Javascript,Css,具体来说,我想做的是使用calcR()函数生成的随机值更改背景。 下面是我为此编写的代码 export default class CB { constructor() { this.backround = "green"; } calcR() { this.r1 = Math.floor(Math.random() * 255 + 1); this.r2 = Math.floor(Math.random() * 255 + 1);

具体来说,我想做的是使用calcR()函数生成的随机值更改背景。 下面是我为此编写的代码

export default class CB {
  constructor() {
    this.backround = "green";
  }
  calcR() {
    this.r1 = Math.floor(Math.random() * 255 + 1);
    this.r2 = Math.floor(Math.random() * 255 + 1);
    this.r3 = Math.floor(Math.random() * 255 + 1);
    console.log(this.r1);
    console.log(this.r2);
    console.log(this.r3);
  }
  cbg() {
    document.body.style.background = `rgb(${this.r1}, ${this.r2}, ${this.r3})`;
  }
}

要向您展示一个端到端的示例,应该这样做:

CB类{
构造函数(){
this.backround=“绿色”;
}
calcR(){
this.r1=Math.floor(Math.random()*255+1);
this.r2=Math.floor(Math.random()*255+1);
this.r3=Math.floor(Math.random()*255+1);
console.log(this.r1);
console.log(this.r2);
console.log(this.r3);
}
cbg(){
document.body.style.background=`rgb(${this.r1},${this.r2},${this.r3})`;
}
}
const cbInstance=new CB();
函数changeBG(){
cbInstance.calcR();
cbInstance.cbg();
}

更改bg
您可以这样做以实现您的结果:

CB类{
构造函数(){
this.backround=“绿色”;
}
calcR(){
this.r1=Math.floor(Math.random()*255+1);
this.r2=Math.floor(Math.random()*255+1);
this.r3=Math.floor(Math.random()*255+1);
this.background=`rgb(${this.r1},${this.r2},${this.r3})`;
归还这个;
}
cbg(){
document.body.style.background=this.background;
归还这个;
}
}
var cb=新的cb();

cb.calcR().cbg()嗯。。。您已经定义了一个类。。。您在哪里实例化了它?然后运行
calcR
,然后再运行
cbg
?您需要导入该类,创建一个实例,调用
calcR
并调用
cbg
,然后再做任何事情。请说明您是如何使用该类的-因为类定义也不会“运行”,请检查browser developer tools控制台中的错误单击此链接查看我在做什么,将相关代码放入问题中